﻿Imports System.Data
Imports System.ComponentModel
Imports System.Collections.ObjectModel
Imports System.Data.SqlClient
Imports System.Security.Permissions
Imports System.Text
Imports System.Windows.Controls.Primitives



Class FLDistFondoInterRepo



    Private negocio As CSGeneralDistribLiq
    Private servicioMonitor As CServicioMonitorFL
    Private lstDataPartida As List(Of CTPartidaSolicitud)
    Private psSelActual As CTPartidaSolicitud
    Private PEJSelActual As CTPartidaEJ
    Private idPSResumenF As Integer
    Private idPEJResumenF As List(Of Integer)
    Private idPSResumenD As Integer
    Private idPEJResumenD As List(Of Integer)
    Private idSecResumenD As List(Of Integer)
    Private NumAjustes As Integer = 0
    Private NumInstrumento As Integer = 0
    Private servicioGenerales As CSServiciosGenerales
    Private lstPSLiberadas As ObservableCollection(Of CTPartidaSolicitud)
    Private lstDistribLiq As List(Of CTFondosDistribLiq) 'Lista para captura de la distribución

    Private lstDistribTotal As List(Of CTDistribLiqReduc) 'Lista para almacenar la distribución de todos los intermediarios para las PS seleccionadas. 
    Private SaldoEstimado As CTDistribLiqReduc            'Variable que mantiene el saldo estimado según lo que se ha distribuido. Para ello IdPS = 0 e IdPEJ = 0 


    Private lstCatalogoTVNG As New List(Of CTCatalogoGenerico)

    Private lstComisionFondo As List(Of CTComisionFondo)     'Lista de Comisiones por fondo 
    


    Public Const LIMITECOLUMNASOLOCOPIADO As Integer = 6
    Public Const FINCIOBLOQUEINTERMEDIARIOS As Integer = 7


    Private Enum ConfigMenuContextual
        COPIADO_Y_PEGADO = 0
        SOLOCOPIADO = 1
    End Enum

    Private tituloMensaje As String = "Resumen Distribución"


    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        servicioGenerales = New CSServiciosGenerales()
        negocio = New CSGeneralDistribLiq()
        servicioMonitor = New CServicioMonitorFL()

          SaldoEstimado = New CTDistribLiqReduc(0, 0)



        If   DistribucionTotalG is Nothing  then 
           lstDistribTotal = New List(Of CTDistribLiqReduc)
        else
            lstDistribTotal = DistribucionTotalG 

             'Se recalculan los saldos estimados por fondo, según todo lo distribuido 
                 SaldoEstimado.LstDistrib.Clear()
                 For Each distrib As CTDistribLiqReduc In lstDistribTotal
                 
                     Dim fondosMontos = distrib.LstDistrib.FindAll(Function(x) x.MontoDistrib <> 0)
                     For Each fondomonto As CTDistribLiqReduc.structDistribFondoXInter In fondosMontos
                         Dim structFondoInter = New CTDistribLiqReduc.structDistribFondoXInter()
                         structFondoInter.CodFondo = fondomonto.CodFondo
                         structFondoInter.MontoDistrib = fondomonto.MontoDistrib
                         SaldoEstimado.LstDistrib.Add(structFondoInter)
                     Next
                 
                 Next
    
        End If
                                                       

        '--------------Inicio Activación de Notificaciones----------------           
        CFLNotificacionDB.CreatePermission()
        Dim modelo = New CTModelMsgNotificacion(Me.Dispatcher, hilo)
        AddHandler modelo.PropertyChanged, AddressOf CountMsg_PropertyChanged
        '--------------Fin Activación de Notificaciones----------------



        txtNumPSLiberadasNvas.Text = "0"
        txtNumAjustes.Text = NumAjustes


        InicializarFechaHora () 'Recuperación de Folios Decalog


        'Carga del combo de TVNG para saldos
        Dim catalogo = New CTCatalogoGenerico()
        lstCatalogoTVNG = catalogo.ObtieneCatalogo(CFLServicioLocalSQLServerDB.__CLAVE_CAT_TVNG__)
        cmbTVNGDistrib.ItemsSource = lstCatalogoTVNG  


        'Inicialización de la lista de Comisiones
         lstComisionFondo = new List(Of CTComisionFondo)



        Mouse.OverrideCursor = Nothing
    End Sub


    Private Sub CountMsg_PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs)
        If hilo > 0 And CType(sender, CTModelMsgNotificacion).numHilo = (hilo - 1) Then
            ActualizarPantallaDistribLiq()
            InicioTabCierreSolicitudes()
        End If

    End Sub


#Region "TAB DISTRIBUCION LIQUIDEZ"
    

   Private Sub chkComisiones_Checked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkComisiones.Checked
      Dim eventoBit =  CBitacoraFRIDA.GenerarEvento (CBitacoraFRIDA.CveEventosBit.ACTIVACION_COMISIONES,CServiciosMacrosSyBaseDB.IDUSUARIO,"FLDistFondoInterRepo->chkComisiones_Checked")    
      MessageBox.Show("Es necesario refrescar para ver los saldos actualizados","Aplicar comisiones",MessageBoxButton.OK,MessageBoxImage.Information)
      eventoBit.ActualizarFechaFinDelEvento ()
   End Sub

   Private Sub chkComisiones_Unchecked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkComisiones.Unchecked
     Dim eventoBit =  CBitacoraFRIDA.GenerarEvento (CBitacoraFRIDA.CveEventosBit.ACTIVACION_COMISIONES,CServiciosMacrosSyBaseDB.IDUSUARIO,"FLDistFondoInterRepo->chkComisiones_Unchecked")    
     MessageBox.Show("Es necesario refrescar para ver los saldos actualizados","Aplicar comisiones",MessageBoxButton.OK,MessageBoxImage.Information)
     eventoBit.ActualizarFechaFinDelEvento ()
   End Sub


    Private Sub FLDistFondoInterRepo_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded

        lstPSLiberadas = New ObservableCollection(Of CTPartidaSolicitud)(negocio.ObtenerPSLiberadasyDistribDeBSO())
        grdPSDistribLiq.ItemsSource = lstPSLiberadas
        grdPSDistribLiq.UpdateLayout()
        txtNumPSLiberadas.Text = grdPSDistribLiq.Items.Count
        txtNumPSLiberadasNvas.Text = 0

        NumAjustes = negocio.ObtenerNumDeAjustesBSO()
        txtNumAjustes.Text = 0
    End Sub


    Private Sub btnRefreshPSLiberadas_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRefreshPSLiberadas.Click

        Mouse.OverrideCursor = Cursors.Wait


        '1) Actualizar Grid PS liberadas

        lstPSLiberadas = New ObservableCollection(Of CTPartidaSolicitud)(negocio.ObtenerPSLiberadasyDistribDeBSO())
        grdPSDistribLiq.ItemsSource = lstPSLiberadas
        grdPSDistribLiq.UpdateLayout()
        txtNumPSLiberadas.Text = grdPSDistribLiq.Items.Count
        txtNumPSLiberadasNvas.Text = 0


        '2) Actualizar Número de partidas de ajuste 
        NumAjustes = negocio.ObtenerNumDeAjustesBSO
        txtNumAjustes.Text = 0


        '3) Actualizar Datos de la selección de la PEJ (Intermediario)

        cmbDistribInter.SelectedItem = Nothing




        Mouse.OverrideCursor = Nothing


    End Sub


    Private Sub grdPSDistribLiq_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdPSDistribLiq.SelectionChanged

        Mouse.OverrideCursor = Cursors.Wait

        '1) Se obtiene la PS seleccionada
        psSelActual = CType(grdPSDistribLiq.SelectedItem, CTPartidaSolicitud) 'Ps Seleccionado

        If psSelActual Is Nothing Then
            Exit Sub
        End If


        '2) Cargar el Combo con las Partidas de Ejecución Correspondientes
        cmbDistribInter.ItemsSource    = psSelActual.LstPEJ        
        cmbDistribInter.UpdateLayout()


        Mouse.OverrideCursor = Nothing


    End Sub


    Private Sub cmbDistribInter_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles cmbDistribInter.SelectionChanged
        Dim sMsgError As String = ""
        Dim importes(2) As Decimal

        Dim valIniText As Double = 0


        Mouse.OverrideCursor = Cursors.Wait


        PEJSelActual = Nothing


        If e.AddedItems Is Nothing Then
            txtImporteTotal.Text = valIniText.ToString("$ ##,##0.00")
            txtImporteDistribParcial.Text = valIniText.ToString("$ ##,##0.00")
            txtImporteRestante.Text = valIniText.ToString("$ ##,##0.00")

            btnRefreshDistribGL_Click(Me.btnRefreshDistribGL, Nothing)

            chkFlexible.IsChecked = False             
            Mouse.OverrideCursor = Nothing

            Exit Sub
        End If



        'Se Carga la información almacenada relacionada con la PEJ seleccionada




        If e.AddedItems.Count = 1 Then

        Dim eventoBit =  CBitacoraFRIDA.GenerarEvento (CBitacoraFRIDA.CveEventosBit.SELECCION_PEJ_EN_DISTRIB,CServiciosMacrosSyBaseDB.IDUSUARIO,"FLDistFondoInterRepo->cmbDistribInter_SelectionChanged")    
        Dim lstBitDet = new List(Of  CTBitEventoDet )

            PEJSelActual = e.AddedItems(0)
            importes = negocio.ObtenerMontosDeDistribXPEJ(PEJSelActual.PartidaEJId, sMsgError)
            If Not sMsgError.Equals("") Then
                Mouse.OverrideCursor = Nothing
                Dim errorBit = eventoBit.GuardarError ("Error al obtener montos: ObtenerMontosDeDistribXPEJ")
                errorBit.GuardarDetalle ("Descripción",sMsgError) 
                MessageBox.Show("Ocurrio un error al consultar los importes, verificar el código: " & errorBit.IdError & "-" & errorBit.IdRegEvento , "Cargar importes de intermediario: Partida PEJ", MessageBoxButton.OK, MessageBoxImage.Exclamation)
                Mouse.OverrideCursor = Cursors.Wait
            End If

            txtImporteTotal.Text = importes(0).ToString("$ ##,##0.00")
            txtImporteDistribParcial.Text = importes(1).ToString("$ ##,##0.00")
            txtImporteRestante.Text = importes(2).ToString("$ ##,##0.00")



            lstBitDet.Add (New CTBitEventoDet ("Importe Total",txtImporteTotal.Text))
            lstBitDet.Add (New CTBitEventoDet ("Importe Distrib parcial",txtImporteDistribParcial.Text))
            lstBitDet.Add (New CTBitEventoDet ("Importe Restante",txtImporteRestante.Text))            
         


            sMsgError = ""
            Dim montoPEJ As Decimal =  negocio.ObtenerMontoDeDistribXPEJDePAJ(PEJSelActual.PartidaEJId,sMsgError)
            If Math.Abs (montoPEJ) > 0 then 
               lstBitDet.Add (New CTBitEventoDet ("Consideración sobre montos","Existe partidas de ajuste con estatus de 'CREADAS' O 'ENVIADAS' con monto total de " & montoPEJ))              
               MessageBox.Show ("Existe partidas de ajuste con estatus de 'CREADAS' O 'ENVIADAS' con monto total de " & montoPEJ & ", es recomendable cancelarlas o aplicarlas antes de realizar la distribución de la partida, dado que la información puede quedar inconsistente", "Distribución de la Liquidez", MessageBoxButton.OK,MessageBoxImage.Exclamation)
            End If


            Dim PejDistribActualAux As CTDistribLiqReduc = lstDistribTotal.Find(Function(x) x.IdPEJ = PEJSelActual.PartidaEJId)
       

            chkFlexible.IsChecked = PEJSelActual.Flexible             
            
          

            txtObservacionPEJ.Text =    PEJSelActual.Observaciones 


            eventoBit.GuardarDetalles (lstBitDet) 
            eventoBit.ActualizarFechaFinDelEvento ()


        Else

            txtImporteTotal.Text = valIniText.ToString("$ ##,##0.00")
            txtImporteDistribParcial.Text = valIniText.ToString("$ ##,##0.00")
            txtImporteRestante.Text = valIniText.ToString("$ ##,##0.00")
            
            
            chkFlexible.IsChecked  = False             

            txtObservacionPEJ.Text  = ""

        End If


        btnRefreshDistribGL_Click(Me.btnRefreshDistribGL, Nothing)

        Mouse.OverrideCursor = Nothing
    End Sub


#Region "Actualización de la pantalla por notificación"

    Private Sub ActualizarPantallaDistribLiq()

        '0) Actualizar la BSO 

        Try
            BSO.CargarBSOActual()
        Catch ex As Exception
            MessageBox.Show("Es probable que la BSO no haya sido cargada correctamente.", "Carga de la BSO", MessageBoxButton.OK, MessageBoxImage.Error)
        End Try

        '1) Actualizar el número de PS liberadas

        txtNumPSLiberadasNvas.Text = Math.Abs(negocio.ObtenerNumPSLiberadasyDistribDeBSO() - grdPSDistribLiq.Items.Count)


        '2) Actualizar Ajustes     

        txtNumAjustes.Text = Math.Abs(negocio.ObtenerNumDeAjustesBSO - NumAjustes)


    End Sub


#End Region


#Region "Notificación para la distribución"

    Private Sub Fondodistrib_PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs)


        Select Case e.PropertyName


            Case "SalDisponible"
                txtSaldoDisp.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("SalDisponible"), lstDistribLiq).ToString("$ ##,##0.00")
            Case "OrdenPend"
                txtOrdenPend.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("OrdenPend"), lstDistribLiq).ToString("$ ##,##0.00")
            Case "PendingCash"
                txtPendingCash.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("PendingCash"), lstDistribLiq).ToString("$ ##,##0.00")
            Case "PendingCashAjust"
                txtPendindAdj.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("PendingCashAjust"), lstDistribLiq).ToString("$ ##,##0.00")
            Case "SaldoDecalogT"
                txtSalDecalog.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("SaldoDecalogT"), lstDistribLiq).ToString("$ ##,##0.00")
            Case "MontoIntermediario"
                txtDistribInter.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("MontoIntermediario"), lstDistribLiq).ToString("$ ##,##0.00")
                txtMontoDistrib.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("MontoIntermediario"), lstDistribLiq).ToString("$ ##,##0.00")
                'Recalcular el saldo remanente de la distribución actual
                Dim MonAux As Decimal = ObtenerMontoRemanente()

                txtMontoRemanente.Text = MonAux.ToString("$ ##,##0.00")
                If MonAux < 0 Then
                    txtMontoRemanente.Foreground = Brushes.Red
                Else
                    txtMontoRemanente.Foreground = Brushes.Black
                End If



        End Select

    End Sub

#End Region


    Private Sub btnRefreshDistribGL_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRefreshDistribGL.Click

        Dim sMsgError As String = ""
        Dim lstFondos As List(Of CTFondoXIntermediario) = Nothing

        Mouse.OverrideCursor = Cursors.Wait


        Dim eventoBit =  CBitacoraFRIDA.GenerarEvento (CBitacoraFRIDA.CveEventosBit.REFRESH_FONDOS_SALDOS,CServiciosMacrosSyBaseDB.IDUSUARIO,"FLDistFondoInterRepo->btnRefreshDistribGL_Click")    


        If PEJSelActual Is Nothing Then
            lstDistribLiq = Nothing
            grdFondoInter.ItemsSource = Nothing
            grdFondoInter.UpdateLayout()
            txtSaldoDisp.Text = ""
            txtOrdenPend.Text = ""
            txtPendingCash.Text = ""
            txtPendindAdj.Text = ""
            txtSalDecalog.Text = ""
            txtDistribInter.Text = ""

            txtMontoDistrib.Text = ""
            txtMontoRemanente.Text = ""
            
            
            eventoBit.ActualizarFechaFinDelEvento ()
            Mouse.OverrideCursor = Nothing

            Exit Sub
        End If

         
        lstFondos = negocio.ObtenerFondosXintermediarioYTVNGDB (PEJSelActual.Intermediario.IdIntermediario,psSelActual.TvngId, sMsgError)

        If (Not sMsgError.Equals("")) OR lstFondos.Count = 0 Then
            Mouse.OverrideCursor = Nothing
           
            If (Not sMsgError.Equals("")) then 
                MessageBox.Show("Occurió un error al consultar la información de fondos: " & sMsgError, "Obtener Información de saldos por fondo", MessageBoxButton.OK, MessageBoxImage.Error)
            else
                MessageBox.Show("No existen fondos relacionados con la TVNG en proceso o con el Intermediario seleccionado. " , "Obtener Información de saldos por fondo", MessageBoxButton.OK, MessageBoxImage.Exclamation )
            End If

                                  
            lstDistribLiq = Nothing
            grdFondoInter.ItemsSource = Nothing
            grdFondoInter.UpdateLayout()

            txtSaldoDisp.Text = ""
            txtOrdenPend.Text = ""
            txtPendingCash.Text = ""
            txtPendindAdj.Text = ""
            txtSalDecalog.Text = ""
            txtDistribInter.Text = ""

            txtMontoDistrib.Text = ""
            txtMontoRemanente.Text = ""

            eventoBit.ActualizarFechaFinDelEvento()

            Exit Sub
        End If

        Dim ToleranciaRemMinXFondo  As Decimal 
        Try
           ToleranciaRemMinXFondo = Convert.ToDecimal (  CServicioLocalSQLServerDB.ObtenerTolRemMinXFondo() )
        Catch ex As Exception
           ToleranciaRemMinXFondo = CSGeneralDistribLiq.__MONTO_TOLERANCIA_REMAMENTE_MINIMO_X_FONDO__
        End Try

        eventoBit.GuadarDetalle ("RemanenteXFondo",ToleranciaRemMinXFondo) 

        Try

            Dim distribEnTrabajo As CTDistribLiqReduc
            distribEnTrabajo = lstDistribTotal.Find(Function(x) x.IdPEJ = PEJSelActual.PartidaEJId)

            

            If chkComisiones.IsChecked = true then 
               lstDistribLiq = negocio.ObtenerSaldosXFondoXInter(lstFondos, SaldoEstimado, distribEnTrabajo, lstComisionFondo)
               
            else
               lstDistribLiq = negocio.ObtenerSaldosXFondoXInter(lstFondos, SaldoEstimado, distribEnTrabajo, nothing)
            End If
            
            CargarSaldosTotales()

            'Notificaciones para fondo-intermediario
            For Each fondo As CTFondosDistribLiq In lstDistribLiq
                AddHandler fondo.PropertyChanged, AddressOf Fondodistrib_PropertyChanged
            Next


            grdFondoInter.ItemsSource = lstDistribLiq
            grdFondoInter.UpdateLayout()


            'Recalcular el saldo remanente de la distribución actual
            Dim montoAux As Decimal
            montoAux = ObtenerMontoRemanente()
            txtMontoRemanente.Text = montoAux.ToString("$ ##,##0.00")

            If montoAux < 0 Then
                txtMontoRemanente.Foreground = Brushes.Red
            Else
                txtMontoRemanente.Foreground = Brushes.Black
            End If


            Mouse.OverrideCursor = Nothing

        Catch ex As Exception
            Mouse.OverrideCursor = Nothing
            Dim errorBit = eventoBit.GuardarError (ex.Message ) 
            MessageBox.Show("Occurió un error al consultar la información de fondos, vuelva a intentarlo. (código:" & errorBit.IdError & "-" & errorBit.IdRegEvento & ")"   , "Obtener Información de saldos por fondo", MessageBoxButton.OK, MessageBoxImage.Error)            
            lstDistribLiq = Nothing
            grdFondoInter.ItemsSource = Nothing
            grdFondoInter.UpdateLayout()
        End Try

        eventoBit.ActualizarFechaFinDelEvento ()

    End Sub

    Private Sub btnGuardarDistrib_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnGuardarDistrib.Click
        
        
                
        Dim lstDistribAux As List(Of CTFondosDistribLiq) = Nothing

        Mouse.OverrideCursor = Cursors.Wait


        Dim eventoBit =  CBitacoraFRIDA.GenerarEvento (CBitacoraFRIDA.CveEventosBit.GUARDAR_DISTRIB_TEMP,CServiciosMacrosSyBaseDB.IDUSUARIO,"FLDistFondoInterRepo->btnGuardarDistrib_Click")    
        Dim lstBitDet = new List(Of  CTBitEventoDet )




        '1) Obtener los valores capturados y cargarlos en la lista total

        If lstDistribLiq Is Nothing Then
            Mouse.OverrideCursor = Nothing
            eventoBit.GuadarDetalle ("Datos almacenado","No existen valores de distribución.")
            eventoBit.ActualizarFechaFinDelEvento ()
            MessageBox.Show("No existen valores de distribución.", "Almacenamiento temporal de distribución", MessageBoxButton.OK, MessageBoxImage.Exclamation)
            Exit Sub
        End If


        Dim distribRedus = New CTDistribLiqReduc(psSelActual.PartidaSolId, PEJSelActual.PartidaEJId)


        lstBitDet.Add(New CTBitEventoDet ("IdPS", psSelActual.PartidaSolId.ToString ()))
        lstBitDet.Add(New CTBitEventoDet ("IdPEJ",PEJSelActual.PartidaEJId.ToString ()))
        

        'Distinción de distribución "PARCIAL" o "TOTAL"


        If PEJSelActual.Flexible   Then
             Dim MontoRestante As Decimal = EliminarFormatoMoneda(txtImporteRestante.Text)
             Dim MontoParcial As Decimal = EliminarFormatoMoneda(txtMontoDistrib.Text)        
             
            If MontoParcial < MontoRestante Then
                distribRedus.EsParcial = True
                distribRedus.MontoTotalDistrib = MontoParcial

            Else
                distribRedus.EsParcial = False
                distribRedus.MontoTotalDistrib = EliminarFormatoMoneda(txtImporteRestante.Text)
            End If            
        Else
            distribRedus.EsParcial = False
            distribRedus.MontoTotalDistrib = EliminarFormatoMoneda(txtImporteRestante.Text)
        End If

        lstBitDet.Add(New CTBitEventoDet ("Flexibilidad", PEJSelActual.Flexible.ToString()))
        lstBitDet.Add(New CTBitEventoDet ("Monto distribuido", distribRedus.MontoTotalDistrib.ToString()))
        lstBitDet.Add(New CTBitEventoDet ("Aplicar comisiones", chkComisiones.IsChecked.ToString()))
            

      

        For Each distribPEJ As CTFondosDistribLiq In lstDistribLiq

            Dim structFondoInter = New CTDistribLiqReduc.structDistribFondoXInter()
            structFondoInter.CodFondo = distribPEJ.CodFondo
            structFondoInter.MontoDistrib = distribPEJ.MontoIntermediario
            distribRedus.LstDistrib.Add(structFondoInter)

            If distribPEJ.CargoComision > 0 or distribPEJ.AbonoComision > 0 then
               lstBitDet.Add (New CTBitEventoDet ("Comision",distribPEJ.CodFondo & ": Cargo=" & distribPEJ.CargoComision & ", Abono= " & distribPEJ.AbonoComision))
            End If

            if distribPEJ.SaldoDecalogCalculado < 0 then 
               lstBitDet.Add (New CTBitEventoDet ("Fondos en Corto",distribPEJ.CodFondo & ": Importe=" & distribPEJ.SaldoDecalogCalculado  & ", Importe Campturado= " & distribPEJ.MontoIntermediario ))
            End If
            
        Next
          


        '2) Se elimina la información almacenada a la distribución correspondiente y se alamcena la nueva
        Dim distribRedusAlmacenada = lstDistribTotal.Find(Function(x) x.IdPs = psSelActual.PartidaSolId And x.IdPEJ = PEJSelActual.PartidaEJId)
        lstDistribTotal.Remove(distribRedusAlmacenada)
        lstDistribTotal.Add(distribRedus)



        '3) Se recalculan los saldos estimados por fondo, según todo lo distribuido 
        SaldoEstimado.LstDistrib.Clear()
        For Each distrib As CTDistribLiqReduc In lstDistribTotal

            Dim fondosMontos = distrib.LstDistrib.FindAll(Function(x) x.MontoDistrib <> 0)
            For Each fondomonto As CTDistribLiqReduc.structDistribFondoXInter In fondosMontos
                Dim structFondoInter = New CTDistribLiqReduc.structDistribFondoXInter()
                structFondoInter.CodFondo = fondomonto.CodFondo
                structFondoInter.MontoDistrib = fondomonto.MontoDistrib

                SaldoEstimado.LstDistrib.Add(structFondoInter)
            Next

        Next

       Dim montoXDistrib As Decimal = ObtenerMontoRemanente() 
       Dim montoDistrib  As Decimal = EliminarFormatoMoneda(txtMontoDistrib.Text)
       If Not chkFlexible.IsChecked then  'Intermediario no Flexible          
          If montoXDistrib <= 0 then 
             MessageBox.Show("La información ha sido almacenada temporalmente, la partida puede ser enviada a Decalog","Almacenamiento Temporal de la Distribución",MessageBoxButton.OK,MessageBoxImage.Information )
          else 
             MessageBox.Show("La información ha sido almacenada temporalmente. Falta por distribuir: " & montoXDistrib.ToString("$ ##,##0.00"),"Almacenamiento Temporal de la Distribución",MessageBoxButton.OK,MessageBoxImage.Information)
          End If

       else 'Intermediario Flexible
           If montoDistrib > 0 then
              MessageBox.Show("La información ha sido almacenada temporalmente, la partida puede ser enviada a Decalog","Almacenamiento Temporal de la Distribución",MessageBoxButton.OK,MessageBoxImage.Information )
           else
              MessageBox.Show("No hay información para almacenar","Almacenamiento Temporal de la Distribución",MessageBoxButton.OK,MessageBoxImage.Information)
           End If
                   
       End If
       



       lstBitDet.Add (New CTBitEventoDet ("Saldo disponible",txtSaldoDisp.Text))
       lstBitDet.Add (New CTBitEventoDet ("Ordenes pendientes",txtOrdenPend.Text))
       lstBitDet.Add (New CTBitEventoDet ("Pending Cash",txtPendingCash.Text))
       lstBitDet.Add (New CTBitEventoDet ("Pending Cash Ajust",txtPendindAdj.Text))
       lstBitDet.Add (New CTBitEventoDet ("Saldo Decalog",txtSalDecalog.Text))       
       eventoBit.GuardarDetalles (lstBitDet) 
       eventoBit.ActualizarFechaFinDelEvento ()




        Mouse.OverrideCursor = Nothing

    End Sub


    Private Sub CargarSaldosTotales()


        Try


            txtSaldoDisp.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("SalDisponible"), lstDistribLiq).ToString("$ ##,##0.00")
            txtOrdenPend.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("OrdenPend"), lstDistribLiq).ToString("$ ##,##0.00")
            txtPendingCash.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("PendingCash"), lstDistribLiq).ToString("$ ##,##0.00")
            txtPendindAdj.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("PendingCashAjust"), lstDistribLiq).ToString("$ ##,##0.00")
            txtSalDecalog.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("SaldoDecalogT"), lstDistribLiq).ToString("$ ##,##0.00")

            txtDistribInter.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("MontoIntermediario"), lstDistribLiq).ToString("$ ##,##0.00")
            txtMontoDistrib.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("MontoIntermediario"), lstDistribLiq).ToString("$ ##,##0.00")

        Catch ex As Exception
            MessageBox.Show("No se pudo obtener los importes totales: " & ex.Message, "Saldos totales", MessageBoxButton.OK, MessageBoxImage.Exclamation)
        End Try



    End Sub

    Private Function ObtenerMontoRemanente() As Decimal
        'Mejorar formato de numero en la función, quitar replace


        Dim importeTotalDistrib As Decimal
        Dim importeDistrib As Decimal
            
        importeTotalDistrib = EliminarFormatoMoneda(txtImporteRestante.Text)
     
        importeDistrib = EliminarFormatoMoneda(txtMontoDistrib.Text)

        Return importeTotalDistrib - importeDistrib

    End Function

    Private Function EliminarFormatoMoneda(ByVal montoFormat As String) As Decimal
        'El formato estándar para moneda es $ ##,##0.00 
        Dim MontoAux As String = ""

        MontoAux = montoFormat.Replace("$", "").Replace(",", "").Replace(" ", "")

        If IsNumeric(MontoAux) Then
            Return Convert.ToDecimal(MontoAux)
        Else
            Return 0D
        End If

    End Function



    'Private Sub btnPruebaFondeo_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnPruebaFondeo.Click


    '    Dim intermediario As CTDistribLiqReduc
    '    Dim PsAux As CTPartidaSolicitud
    '    Dim sMsgError As String = ""

    '    Dim index As Integer = 0 'VARIABLE SOLO PARA PRUEBAS

    '    Dim resultado As CSGeneralDistribLiq.ESTADOTRANSDISTRIB   ' Variable para almacenar temporalmente el estado de la transacción. 


    '    intermediario = lstDistribTotal(index)
    '    PsAux = BSO.LstPS.Find(Function(x) x.PartidaSolId = intermediario.IdPs)


    '    resultado = negocio.FondeoReportosXIntermediario(intermediario, PsAux, sMsgError)

    '    If resultado = CSGeneralDistribLiq.ESTADOTRANSDISTRIB.COMPLETA Or resultado = CSGeneralDistribLiq.ESTADOTRANSDISTRIB.ENVIADA_A_DECALOG Then
    '        MessageBox.Show("Todo correcto", "Fondeo Reportos", MessageBoxButton.OK, MessageBoxImage.Information)



    '        'Se recalculan los saldos estimados por fondo, según todo lo distribuido 
    '        lstDistribTotal.RemoveAt(index)

    '        SaldoEstimado.LstDistrib.Clear()
    '        For Each distrib As CTDistribLiqReduc In lstDistribTotal

    '            Dim fondosMontos = distrib.LstDistrib.FindAll(Function(x) x.MontoDistrib <> 0)
    '            For Each fondomonto As CTDistribLiqReduc.structDistribFondoXInter In fondosMontos
    '                Dim structFondoInter = New CTDistribLiqReduc.structDistribFondoXInter()
    '                structFondoInter.CodFondo = fondomonto.CodFondo
    '                structFondoInter.MontoDistrib = fondomonto.MontoDistrib

    '                SaldoEstimado.LstDistrib.Add(structFondoInter)
    '            Next

    '        Next



    '        'Limpia la

    '        ActualizarPantallaDistribLiq()
    '        btnRefreshPSLiberadas_Click(Me.btnRefreshPSLiberadas, Nothing)

    '    Else

    '        MessageBox.Show("Error: " & sMsgError & ". Estado: " & resultado, "Fondeo Reportos", MessageBoxButton.OK, MessageBoxImage.Error)
    '    End If


    'End Sub





#Region "EDICION GRID (CAPTURA)"

    Private Sub grdFondoInter_CellEditEnding(ByVal sender As System.Object, ByVal e As System.Windows.Controls.DataGridCellEditEndingEventArgs) Handles grdFondoInter.CellEditEnding
        Dim txtContenidoCelda As Object

        Try

            If e.EditAction <> DataGridEditAction.Cancel Then

                If Not sender.CurrentItem Is Nothing Then

                    txtContenidoCelda = sender.Columns(e.Column.DisplayIndex).GetCellContent(CType(e.Row.Item, CTFondosDistribLiq))

                    If Not IsNumeric(txtContenidoCelda.Text) Then
                        CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                    Else

                        Dim MontoRemanente As Decimal = EliminarFormatoMoneda(txtMontoRemanente.Text)
                        Dim MontoAnteFondo As Decimal = CType(e.Row.Item, CTFondosDistribLiq)(e.Column.DisplayIndex)
                        Dim montoPosible As Decimal = MontoRemanente + MontoAnteFondo - Convert.ToDecimal(txtContenidoCelda.Text)

                        If montoPosible < 0   Then
                            CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                        Else

                            Dim saldoCalc As Decimal = CType(e.Row.Item, CTFondosDistribLiq).SaldoDecalogCalculado + MontoAnteFondo - Convert.ToDecimal(txtContenidoCelda.Text)

                            If (saldoCalc < 0) And Convert.ToDouble(txtContenidoCelda.Text) > 0 Then
                                If MessageBox.Show("El fondo: " & CType(e.Row.Item, CTFondosDistribLiq).CodFondo & " quedará corto.", "Fondo con saldo en corto", MessageBoxButton.OKCancel, MessageBoxImage.Question) = MessageBoxResult.Cancel Then
                                    CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                                End If
                            End If

                        End If

                    End If


                Else
                    CType(sender, DataGrid).CancelEdit(DataGridEditingUnit.Cell)
                End If


            End If


        Catch ex As Exception
            'No se necesita el manejo de la excepción, en todo caso se puede mostrar un mensaje personalizado (lo cual quedará a petición del usuario).
        End Try

    End Sub


    Private Sub grdFondoInter_MouseRightButtonUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles grdFondoInter.MouseRightButtonUp

        Dim objDepend As DependencyObject = e.OriginalSource
        Dim celda As DataGridCell = Nothing


        Me.grdFondoInter.ContextMenu = Nothing
        While Not objDepend Is Nothing

            If objDepend.GetType().Name = "DataGridCell" Then
                celda = objDepend

                If celda.IsSelected = False Then
                    Me.grdFondoInter.UnselectAllCells()
                    celda.IsSelected = True
                End If

                celda.Focus()

                If celda.Column.DisplayIndex <= LIMITECOLUMNASOLOCOPIADO OR celda.Column.DisplayIndex > FINCIOBLOQUEINTERMEDIARIOS  Then
                    Me.grdFondoInter.ContextMenu = AgregarMenuContextual(ConfigMenuContextual.SOLOCOPIADO)
                Else
                    Me.grdFondoInter.ContextMenu = AgregarMenuContextual(ConfigMenuContextual.COPIADO_Y_PEGADO)
                End If

                Exit While
            End If

            objDepend = VisualTreeHelper.GetParent(objDepend)
        End While




    End Sub


    Private Sub grdFondoInter_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles grdFondoInter.PreviewKeyDown


        If e.Key = Key.Apps Then

            If grdFondoInter.CurrentCell.Column.DisplayIndex <= LIMITECOLUMNASOLOCOPIADO Or grdFondoInter.CurrentCell.Column.DisplayIndex > FINCIOBLOQUEINTERMEDIARIOS Then 'Condición según el negocio
                Me.grdFondoInter.ContextMenu = AgregarMenuContextual(ConfigMenuContextual.SOLOCOPIADO)
            Else
                Me.grdFondoInter.ContextMenu = AgregarMenuContextual(ConfigMenuContextual.COPIADO_Y_PEGADO)
            End If
        End If



        If Keyboard.Modifiers = ModifierKeys.Control AndAlso e.Key = Key.C Then
            Try
                If copiarCeldas(Me.grdFondoInter, "General.CTFondosDistribLiq") = False Then
                    e.Handled = True 'Se indica que el evento ha sido manejado antes del mensaje, ya que este renderiza la pantalla
                    MessageBox.Show("El rango de celdas seleccionado no es correcto", "Copiar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
                End If

            Catch ex As Exception
                e.Handled = True
                MessageBox.Show("Error TI500. Error al intentar copiar celdas: " & ex.Message, "Copiado", MessageBoxButton.OK, MessageBoxImage.Error)
            End Try

        End If

        If Keyboard.Modifiers = ModifierKeys.Control AndAlso e.Key = Key.V Then

            Try
                Dim col As Integer = Me.grdFondoInter.CurrentCell.Column.DisplayIndex
                Dim row As Integer = Me.grdFondoInter.Items.IndexOf(CType(Me.grdFondoInter.CurrentCell.Item, CTFondosDistribLiq))
                Dim celda As DataGridCell = ObtenerCelda(Me.grdFondoInter, row, col)

                If col > LIMITECOLUMNASOLOCOPIADO And col <= FINCIOBLOQUEINTERMEDIARIOS Then

                    Me.grdFondoInter.CancelEdit()
                    pegarDatos(Me.grdFondoInter, "General.CTFondosDistribLiq", CUtileria.Condiciones.sinCondicion)
                    e.Handled = True
                End If



            Catch ex As Exception
                Me.grdFondoInter.CancelEdit(DataGridEditingUnit.Cell)
                e.Handled = True
                MessageBox.Show(ex.Message, "Pegar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
            End Try

        End If

        If e.Key = Key.Delete Then

            Try
                Dim col As Integer = Me.grdFondoInter.CurrentCell.Column.DisplayIndex
                Dim row As Integer = Me.grdFondoInter.Items.IndexOf(CType(Me.grdFondoInter.CurrentCell.Item, CTFondosDistribLiq))
                Dim celda As DataGridCell = ObtenerCelda(Me.grdFondoInter, row, col)


                If Not celda.IsEditing Then
                    borraDatosSeleccionados(Me.grdFondoInter)
                    Me.grdFondoInter.UnselectAllCells()
                End If


            Catch ex As Exception
                MessageBox.Show("Error TI500. " & ex.Message, "Borrar contenido de celdas", MessageBoxButton.OK, MessageBoxImage.Error)
            End Try

        End If



    End Sub


    Private Function AgregarMenuContextual(ByVal opcion As ConfigMenuContextual) As ContextMenu
        Dim miMenuContextual As New ContextMenu
        Dim mnuCopia As New System.Windows.Controls.MenuItem
        Dim mnuPegar As New System.Windows.Controls.MenuItem



        mnuCopia.Header = "Copiar"
        miMenuContextual.Items.Add(mnuCopia)
        AddHandler mnuCopia.Click, AddressOf mnuCopiar_click


        'Este case esta preparado para extender la funcionalidad de las opciones del menú contextual
        Select Case opcion
            Case ConfigMenuContextual.COPIADO_Y_PEGADO
                mnuPegar.Header = "Pegar"
                miMenuContextual.Items.Add(mnuPegar)
                AddHandler mnuPegar.Click, AddressOf mnuPegar_click
        End Select

        Return miMenuContextual

    End Function



#End Region


#Region "MENU CONTEXTUAL"

    Private Sub mnuPegar_click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Try
            pegarDatos(Me.grdFondoInter, "General.CTFondosDistribLiq", CUtileria.Condiciones.sinCondicion)
        Catch ex As Exception
            MessageBox.Show("Error TI500. " & ex.Message, "Pegar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
        End Try

    End Sub

    Private Sub mnuCopiar_click(ByVal sender As Object, ByVal e As RoutedEventArgs)

        Try
            If copiarCeldas(Me.grdFondoInter, "General.CTFondosDistribLiq") = False Then
                MessageBox.Show("El rango de celdas seleccionado no es correcto", "Copiar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
            End If
        Catch ex As Exception
            MessageBox.Show("Error TI500. Error al intentar copiar celdas: " & ex.Message, "Copiado", MessageBoxButton.OK, MessageBoxImage.Error)
        End Try

    End Sub


#End Region


#Region "Funciones comunes"


    Private Sub borraDatosSeleccionados(ByRef gridDeDatos As DataGrid)

        Dim lstInterAux As List(Of CTFondosDistribLiq)

        lstInterAux = gridDeDatos.ItemsSource

        Try
            For Each celda As DataGridCellInfo In gridDeDatos.SelectedCells
                Dim col As Integer = celda.Column.DisplayIndex
                Dim row As Integer = gridDeDatos.Items.IndexOf(CType(celda.Item, CTFondosDistribLiq))

                If col > LIMITECOLUMNASOLOCOPIADO And (col > LIMITECOLUMNASOLOCOPIADO And col <= FINCIOBLOQUEINTERMEDIARIOS) Then

                    Dim rowData As DataGridRow = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(row)
                    Dim cellContent As Object = gridDeDatos.Columns(col).GetCellContent(rowData)

                    cellContent.Text = String.Format("{0:N}", CTFondosDistribLiq.ValorInicalColumna(col))
                    lstInterAux(row)(col) = CTFondosDistribLiq.ValorInicalColumna(col)


                End If

            Next

        Catch ex As Exception
            Throw ex
        End Try


    End Sub

    Private Sub pegarDatos(ByRef gridDeDatos As DataGrid, ByVal sTipo As String, ByVal condicion As CUtileria.Condiciones)

        Dim lstInterAux As Object = gridDeDatos.ItemsSource
        Dim datos As CDatosEnFormatoX
        Dim ttipo As System.Type = Type.GetType(sTipo)



        Dim bCONDICIONNONEGATIVOS = False
        Dim bCONDICIONMAYOTMONTOMAX = False


        datos = CUtileria.ObtenerDatosClipboard(vbLf, vbTab)

        '1) Validaciones: obtener información del portapapeles

        If datos.Datos.length = 0 Then
            Exit Sub
        End If


        If datos Is Nothing Then
            Throw New Exception("No se pudo copiar los datos")
        End If

        '2) Validaciones: compatibilidad  

        Dim colTot As Integer = gridDeDatos.Columns.Count
        Dim rowTot As Integer = gridDeDatos.Items.Count

        Dim colActual As Integer = gridDeDatos.CurrentCell.Column.DisplayIndex
        Dim rowActual As Integer = gridDeDatos.Items.IndexOf(CTypeDynamic(gridDeDatos.CurrentCell.Item, ttipo))


        'Validar renglones

        If datos.NumeroRenglones > ((rowTot - (rowActual + 1)) + 1) Then
            Throw New Exception("No coinciden las dimensiones de datos a pegar (R)")
        End If

        If datos.NumeroColumnas.Max > ((colTot - (colActual + 1)) + 1) Then
            Throw New Exception("No coinciden las dimensiones de datos a pegar (C)")
        End If

        '2) Realizar copiado  

        Dim i As Integer = 0
        Dim j As Integer = 0

        Dim coontador As Integer = 0
        Dim limRow As Integer = (rowActual + (datos.NumeroRenglones - 1))

        gridDeDatos.UnselectAllCells()


        Try

            For i = rowActual To limRow
                Dim limCol As Integer = (colActual + (datos.NumeroColumnas(coontador) - 1))

                For j = colActual To limCol



                    If j <> FINCIOBLOQUEINTERMEDIARIOS Then
                        Continue For
                    End If

                    If datos.Datos(i - rowActual)(j - colActual) <> vbLf And (Not CType(datos.Datos(i - rowActual)(j - colActual), String).Trim().Equals("")) Then
                        Dim row As DataGridRow = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(i)
                        Dim cellContent As Object = gridDeDatos.Columns(j).GetCellContent(row)
                        Dim auxImp As Decimal
                        auxImp = CType(datos.Datos(i - rowActual)(j - colActual), Decimal)



                         

                        Dim MontoRemanente As Decimal = EliminarFormatoMoneda(txtMontoRemanente.Text)
                        Dim MontoAnteFondo As Decimal = gridDeDatos.Items(i)(j)
                        Dim montoPosible As Decimal = MontoRemanente + MontoAnteFondo - auxImp

                        If montoPosible >= 0 Then
                            lstDistribLiq(i)(j) = auxImp
                            lstInterAux(i)(j) = auxImp
                            cellContent.Text = String.Format("{0:N}", lstInterAux(i)(j))
                            seleccionarcelda(gridDeDatos, i, j)
                        Else
                            bCONDICIONMAYOTMONTOMAX = True
                        End If



                        If auxImp < 0 Then
                            bCONDICIONNONEGATIVOS = True
                        End If


                    End If
                Next
                coontador += 1
            Next



            If bCONDICIONMAYOTMONTOMAX = True Then
                Throw New Exception("No se pudieron pegar todos los datos, ya que algunos de ellos sobrepasaban el importe máximo asignado")
            End If


            If bCONDICIONNONEGATIVOS = True Then
                Throw New Exception("Los valores negativos no pudieron ser pegados: no están permitidos")
            End If


        Catch ex As Exception


            If bCONDICIONMAYOTMONTOMAX = True Or bCONDICIONNONEGATIVOS = True Then
                Throw ex
            Else
                Throw New Exception("No se pudo terminar de copiar los datos debido a que no coinciden con el formato especificado para cada celda", ex)
            End If


        End Try


    End Sub

    Private Function copiarCeldas(ByRef gridDeDatos As DataGrid, ByVal sTipo As String) As Boolean

        Dim ttipo As System.Type = Type.GetType(sTipo)

        Try

            Dim lstInterAux As Object = gridDeDatos.ItemsSource


            Dim datos As New System.Text.StringBuilder
            Dim copiadoCorrecto As Boolean = True


            Dim colIni As Integer = Integer.MaxValue
            Dim rowIni As Integer = Integer.MaxValue

            Dim colFin As Integer = Integer.MinValue
            Dim rowFin As Integer = Integer.MinValue


            Dim i As Integer = 0
            Dim j As Integer = 0


            Dim columnasIndex(gridDeDatos.SelectedCells.Count - 1) As Integer
            Dim renglonesIndex(gridDeDatos.SelectedCells.Count - 1) As Integer

            For Each celda As DataGridCellInfo In gridDeDatos.SelectedCells

                renglonesIndex(i) = gridDeDatos.Items.IndexOf(CTypeDynamic(celda.Item, ttipo))
                columnasIndex(j) = celda.Column.DisplayIndex
                i += 1
                j += 1
            Next


            rowIni = renglonesIndex.Min()
            rowFin = renglonesIndex.Max()

            colIni = columnasIndex.Min()
            colFin = columnasIndex.Max()


            For i = rowIni To rowFin
                For j = colIni To colFin
                    If EsSeleccionadaLaCelda(gridDeDatos, i, j) Then
                        datos.Append(lstInterAux(i)(j).ToString() & vbTab)
                    'Else
                    '    copiadoCorrecto = False
                    '    GoTo fuera
                    End If
                Next

                datos.Remove(datos.Length - 1, 1)
                datos.Append(vbLf)
            Next


            datos.Remove(datos.Length - 1, 1)



fuera:
            If copiadoCorrecto = True Then
                Clipboard.Clear()
                Clipboard.SetText(datos.ToString())
                Return True
            Else
                Return False
            End If


        Catch ex As Exception

            Throw ex

        End Try




    End Function

    Private Function EsSeleccionadaLaCelda(ByRef gridDeDatos As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer) As Boolean

        Dim row As DataGridRow = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(indexRow)
        Dim cellContent As Object = gridDeDatos.Columns(indexCol).GetCellContent(row)


        Dim objDepend As DependencyObject = cellContent
        Dim celda As DataGridCell = Nothing

        While Not objDepend Is Nothing

            If objDepend.GetType().Name = "DataGridCell" Then
                celda = objDepend

                If celda.IsSelected = True Then
                    Return True
                Else
                    Return False
                End If

            End If

            objDepend = VisualTreeHelper.GetParent(objDepend)
        End While

        Return False

    End Function

    Private Sub seleccionarcelda(ByRef gridDeDatos As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer)

        Dim row As DataGridRow = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(indexRow)
        Dim cellContent As TextBlock = gridDeDatos.Columns(indexCol).GetCellContent(row)


        Dim objDepend As DependencyObject = cellContent
        Dim celda As DataGridCell = Nothing


        While Not objDepend Is Nothing

            If objDepend.GetType().Name = "DataGridCell" Then
                celda = objDepend

                If celda.IsSelected = False Then
                    celda.IsSelected = True
                    celda.Focus()
                    Exit While
                End If

            End If

            objDepend = VisualTreeHelper.GetParent(objDepend)
        End While

    End Sub

    Private Function ObtenerCelda(ByRef miDataGrid As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer) As DataGridCell

        Try
            Dim row As DataGridRow = miDataGrid.ItemContainerGenerator.ContainerFromIndex(indexRow)
            Dim cellContent As Object = miDataGrid.Columns(indexCol).GetCellContent(row)

            Dim objDepend As DependencyObject = cellContent
            Dim celda As DataGridCell = Nothing

            While Not objDepend Is Nothing

                If objDepend.GetType().Name = "DataGridCell" Then
                    celda = objDepend
                    Return celda
                End If
                objDepend = VisualTreeHelper.GetParent(objDepend)
            End While
        Catch ex As Exception
            Throw ex
        End Try

        Return Nothing
    End Function


#End Region

#End Region


#Region "TAB RESUMEN DISTRIBUCION"
    Private Sub tcLiquidez_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
        Try
            If (e.OriginalSource.GetType Is GetType(TabControl)) Then
                Dim objCurrentSelectedTabItem As TabItem
                If (e.AddedItems IsNot Nothing AndAlso e.AddedItems.Count > 0) Then
                    objCurrentSelectedTabItem = e.AddedItems(0)
                    If (objCurrentSelectedTabItem IsNot Nothing) Then
                        If (objCurrentSelectedTabItem.Name = Me.tabResumenDistribucion.Name) Then
                            BSO.CargarBSOActual()
                            InicioTabResumenDist()
                        End If

                        If (objCurrentSelectedTabItem.Name = Me.tabCierreSolicitudes.Name) Then
                            InicioTabCierreSolicitudes()
                        End If
                    End If
                End If

            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub expFrida_Expanded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles expFrida.Expanded
        If Me.grdResumendDist.Items.Count() = 0 Then
            Me.expFrida.IsExpanded = False
            MessageBox.Show("No existen valores de distribución por guardar en FRIDA", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Exclamation)
        Else
            Me.grdResumendDist.Items.Refresh()
            Me.grdResumendDist.UpdateLayout()
            Me.grdOrdenes.UpdateLayout()
        End If
    End Sub

    Private Sub expDecalog_Expanded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles expDecalog.Expanded
        If Me.grdResumendDistDecalog.Items.Count() = 0 Then
            Me.expDecalog.IsExpanded = False
            MessageBox.Show("No existen valores de distribución para generar ordenes en DECALOG", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Exclamation)
        Else
            Me.grdResumendDistDecalog.Items.Refresh()
            Me.grdResumendDistDecalog.UpdateLayout()
            Me.grdOrdenesDecalog.UpdateLayout()
        End If
    End Sub

    Private Sub InicioTabResumenDist()

        Mouse.OverrideCursor = Cursors.Wait
        Me.cmbDistribInter.ItemsSource = Nothing
        idPSResumenF = Nothing
        idPEJResumenF = New List(Of Integer)
        idPSResumenD = Nothing
        idPEJResumenD = New List(Of Integer)
        idSecResumenD = New List(Of Integer)

        'EXPANDER FRIDA
        Me.btnGuardarFrida.Visibility = Windows.Visibility.Hidden
        Me.btnEliminarDist.Visibility = Windows.Visibility.Hidden
        Me.btnModificarDist.Visibility = Windows.Visibility.Hidden
        Me.grdResumendDist.ItemsSource = Nothing
        Me.grdResumendDist.Visibility = Windows.Visibility.Hidden

        Dim lstDistribuciones As List(Of CTDistribLiqReduc) = lstDistribTotal.FindAll(Function(x) x.MontoRemanente = 0 And x.MontoTotalDistrib > 0)
        Dim lstPartidas As List(Of CTPartidaSolicitud) = New List(Of CTPartidaSolicitud)()
        Dim partida As CTPartidaSolicitud = Nothing
        For Each fondodist As CTDistribLiqReduc In lstDistribuciones
            Dim idPS = fondodist.IdPs
            If lstPartidas.Find(Function(x) x.PartidaSolId = idPS) Is Nothing Then
                partida = New CTPartidaSolicitud()
                partida = BSO.LstPS.Find(Function(x) x.PartidaSolId = idPS)
                lstPartidas.Add(partida)
            End If

        Next
        lstPartidas = lstPartidas.OrderBy(Function(x) x.PartidaSolId).ToList()
        Dim lstPartidasOC = New ObservableCollection(Of CTPartidaSolicitud)(lstPartidas)
        Me.txtDistInterFrida.Text = lstPartidas.Count()
        Me.grdResumendDist.ItemsSource = lstPartidasOC
        If Me.grdResumendDist.Items.Count() > 0 Then
            Me.grdResumendDist.Visibility = Windows.Visibility.Visible
        End If
        Me.grdResumendDist.UpdateLayout()
        Me.grdOrdenes.ItemsSource = Nothing

        
        'EXPANDER DECALOG
        Me.btnGuardarDecalog.Visibility = Windows.Visibility.Hidden
        Me.grdResumendDistDecalog.ItemsSource = Nothing
        Me.grdResumendDistDecalog.Visibility = Windows.Visibility.Hidden
        Me.nmInstrumento.Visibility = Windows.Visibility.Hidden
        Me.txtInstrumento.Visibility = Windows.Visibility.Hidden

        lstPartidas = BSO.LstPS.FindAll(Function(x) x.FolioEnviadoDecalog > 0 and x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.EN_DISTRIBUCION)
        lstPartidas = lstPartidas.OrderBy(Function(x) x.PartidaSolId).ToList()
        lstPartidasOC = New ObservableCollection(Of CTPartidaSolicitud)(lstPartidas)
        Me.txtDistInterDecalog.Text = lstPartidas.Count()
        Me.grdResumendDistDecalog.ItemsSource = lstPartidasOC
        Me.grdResumendDistDecalog.Items.Refresh
        If Me.grdResumendDistDecalog.Items.Count() > 0 Then
            Me.grdResumendDistDecalog.Visibility = Windows.Visibility.Visible
        End If
        Me.grdResumendDistDecalog.UpdateLayout()
        Me.grdOrdenesDecalog.ItemsSource = Nothing
        
        Me.expDecalog.IsExpanded = False
        Me.expFrida.IsExpanded = False

        Me.txtFechaBSO.Text = BSO.FecOperacion.ToString("dd/MM/yyyy")
        ActualizarPantallaDistribLiq()
        btnRefreshPSLiberadas_Click(Me.btnRefreshPSLiberadas, Nothing)
        Mouse.OverrideCursor = Nothing
    End Sub

    Private Sub ActualizaExps()
        Dim ps As Integer = Me.grdResumendDist.SelectedIndex
        Dim psD As Integer = Me.grdResumendDistDecalog.SelectedIndex
        Dim countbefore As Integer = Me.grdResumendDistDecalog.Items.Count()
        Dim expF As Boolean = Me.expFrida.IsExpanded
        Dim expD As Boolean = Me.expDecalog.IsExpanded
        BSO.CargarBSOActual()
        InicioTabResumenDist()
        If ps <> -1 and ps < Me.grdResumendDist.Items.Count() Then
             Me.grdResumendDist.SelectedIndex = ps
             Me.expFrida.IsExpanded = expF
             Me.grdResumendDist.UpdateLayout()
             grdResumendDist_SelectionChanged(Nothing, Nothing)
        Else
            If Me.grdResumendDist.Items.Count() > 0 then
                Me.grdResumendDist.SelectedIndex = Me.grdResumendDist.Items.Count() - 1
                Me.expFrida.IsExpanded = expF
                Me.grdResumendDist.UpdateLayout()
                grdResumendDist_SelectionChanged(Nothing, Nothing)
            Else
                Me.btnGuardarFrida.Visibility = Windows.Visibility.Hidden
                Me.btnEliminarDist.Visibility = Windows.Visibility.Hidden
                Me.btnModificarDist.Visibility = Windows.Visibility.Hidden
                Me.grdResumendDist.ItemsSource = Nothing
                Me.grdResumendDist.Visibility = Windows.Visibility.Hidden
                Me.grdOrdenes.Visibility = Windows.Visibility.Hidden
                Me.expFrida.IsExpanded = False
            End If
        End If

        If countbefore > 0 Then
            If psD <> -1 and psD < Me.grdResumendDistDecalog.Items.Count() Then
                 Me.grdResumendDistDecalog.SelectedIndex = psD
                 Me.expDecalog.IsExpanded = expD
                 Me.grdResumendDistDecalog.UpdateLayout()
                 grdResumendDistDecalog_SelectionChanged(Nothing, Nothing)
            Else
                If Me.grdResumendDistDecalog.Items.Count() > 0 then
                    Me.grdResumendDistDecalog.SelectedIndex = Me.grdResumendDistDecalog.Items.Count() - 1
                    Me.expDecalog.IsExpanded = expD
                    Me.grdResumendDistDecalog.UpdateLayout()
                    grdResumendDistDecalog_SelectionChanged(Nothing, Nothing)
                Else
                    Me.btnGuardarDecalog.Visibility = Windows.Visibility.Hidden
                    Me.grdResumendDistDecalog.ItemsSource = Nothing
                    Me.grdResumendDistDecalog.Visibility = Windows.Visibility.Hidden
                    Me.grdOrdenesDecalog.Visibility = Windows.Visibility.Hidden
                    Me.nmInstrumento.Visibility = Windows.Visibility.Hidden
                    Me.txtInstrumento.Visibility = Windows.Visibility.Hidden
                    Me.expDecalog.IsExpanded = False
                End If
            End If
        Else
            Me.grdResumendDistDecalog.SelectedIndex = Nothing
            Me.grdResumendDistDecalog.UpdateLayout()
        End If

        If  Me.grdResumendDistDecalog.Items.Count() = 1 or Me.grdOrdenesDecalog.Visibility = Windows.Visibility.Hidden Or Me.grdOrdenesDecalog.Visibility = Not Windows.Visibility.Visible Then
            Me.nmInstrumento.Visibility = Windows.Visibility.Hidden
            Me.txtInstrumento.Visibility = Windows.Visibility.Hidden
            Me.btnGuardarDecalog.Visibility = Windows.Visibility.Hidden
            Me.grdResumendDistDecalog.SelectedIndex = Nothing
            Me.grdResumendDistDecalog.SelectedItem = Nothing
        End If
    End Sub

    Private Sub grdResumendDist_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdResumendDist.SelectionChanged
        
        If Me.grdResumendDist.Items.Count() > 0 Then
            Mouse.OverrideCursor = Cursors.Wait
            Me.grdOrdenes.ItemsSource = Nothing
            Dim partida = CType(Me.grdResumendDist.SelectedItem, CTPartidaSolicitud)
            idPSResumenF = partida.PartidaSolId
            idPEJResumenF = New List(Of Integer)
            If partida Is Nothing Then
                Me.btnGuardarFrida.Visibility = Windows.Visibility.Hidden
                Me.btnEliminarDist.Visibility = Windows.Visibility.Hidden
                Me.btnModificarDist.Visibility = Windows.Visibility.Hidden
                Me.grdOrdenes.Visibility = Windows.Visibility.Hidden
                idPSResumenF = Nothing
                Exit Sub
            End If

            Me.btnGuardarFrida.Visibility = Windows.Visibility.Visible
            Me.btnEliminarDist.Visibility = Windows.Visibility.Visible
            Me.btnModificarDist.Visibility = Windows.Visibility.Visible
            Dim dt As New DataTable("ResumenDistribuciones")
            Dim lstDistribuciones As List(Of CTDistribLiqReduc) = lstDistribTotal.FindAll(Function(x) x.MontoRemanente = 0 And x.MontoTotalDistrib > 0 And x.IdPs = partida.PartidaSolId)
            Dim columna As DataColumn = New DataColumn("FONDO", System.Type.GetType("System.String"))
            dt.Columns.Add(columna)
            For Each fondodist As CTDistribLiqReduc In lstDistribuciones
                Dim idPej = fondodist.IdPEJ
                Dim pej = BSO.LstPEJ.Find(Function(x) x.PartidaEJId = idPej)
                columna = New DataColumn(pej.Intermediario.NombreIntermediario + " - " + pej.Tasa.ToString().Replace(".", ",") + "%", System.Type.GetType("System.String"))
                dt.Columns.Add(columna)
            Next

            columna = New DataColumn("IDPEJ", System.Type.GetType("System.Int32"))
            dt.Columns.Add(columna)

            Dim registroTotal = dt.NewRow()
            registroTotal("FONDO") = "TOTAL"
            For Each fondodist As CTDistribLiqReduc In lstDistribuciones

                Dim list = fondodist.LstDistrib.FindAll(Function(x) x.MontoDistrib > 0)
                Dim colTotal As String = ""
                Dim valTotal As Double = 0
                For index As Integer = 0 To (list.Count() - 1)
                    
                    Dim registro = dt.NewRow()
                    Dim idPej = fondodist.IdPEJ
                    Dim pej = BSO.LstPEJ.Find(Function(x) x.PartidaEJId = idPej)

                    registro("FONDO") = list(index).CodFondo
                    registro(pej.Intermediario.NombreIntermediario + " - " + pej.Tasa.ToString().Replace(".", ",") + "%") = list(index).MontoDistrib.ToString("#,###.00")
                    registro("IDPEJ") = idPej
                    
                    colTotal = pej.Intermediario.NombreIntermediario + " - " + pej.Tasa.ToString().Replace(".", ",") + "%"
                    valTotal = valTotal + list(index).MontoDistrib

                    dt.Rows.Add(registro)
                Next
                registroTotal(colTotal) = valTotal.ToString("#,###.00")
            
            Next
            dt.Rows.Add(registroTotal)
            Dim view = New DataView(dt)
            Me.grdOrdenes.ItemsSource = view
            If Me.grdOrdenes.Columns.Count() > 0 then
                Me.grdOrdenes.Columns(Me.grdOrdenes.Columns.Count() - 1).Width = 2
                Me.grdOrdenes.Columns(Me.grdOrdenes.Columns.Count() - 1).Visibility = Windows.Visibility.Hidden
                Me.grdOrdenes.Visibility = System.Windows.Visibility.Visible
                Me.grdOrdenes.UpdateLayout()
                'Color Total
                Dim fila = Me.grdOrdenes.Items.Count() - 1
                For index As Integer = 0 To (Me.grdOrdenes.Columns.Count() - 2)
                    Dim celdaTotal As DataGridCell = getCell(fila, index, Me.grdOrdenes)
                    celdaTotal.Background = Brushes.DarkBlue
                    celdaTotal.Foreground = Brushes.White
                    celdaTotal.BorderBrush = Brushes.DarkBlue
                    celdaTotal.FontWeight = FontWeights.Bold
                Next
            End If
            
            
            Mouse.OverrideCursor = Nothing
        End If
        

    End Sub

    Private Sub grdResumendDistDecalog_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdResumendDistDecalog.SelectionChanged
        
        If Me.grdResumendDistDecalog.Items.Count() > 0 Then
            Mouse.OverrideCursor = Cursors.Wait
            Me.grdOrdenesDecalog.ItemsSource = Nothing
            Dim partida = CType(Me.grdResumendDistDecalog.SelectedItem, CTPartidaSolicitud)
            
            If partida Is Nothing Then
                Me.nmInstrumento.Visibility = Windows.Visibility.Hidden
                Me.txtInstrumento.Visibility = Windows.Visibility.Hidden
                Me.btnGuardarDecalog.Visibility = Windows.Visibility.Hidden
                Me.grdOrdenesDecalog.Visibility = Windows.Visibility.Hidden
                idPSResumenD = Nothing
                Exit Sub
            End If

            idPSResumenD = partida.PartidaSolId
            idPEJResumenD = New List(Of Integer)
            idSecResumenD = New List(Of Integer)


            If partida.TvngId > 4 Then
                Me.nmInstrumento.Visibility = Windows.Visibility.Visible
                Me.txtInstrumento.Visibility = Windows.Visibility.Visible
            Else
                Me.nmInstrumento.Visibility = Windows.Visibility.Hidden
                Me.txtInstrumento.Visibility = Windows.Visibility.Hidden
            End If

            Me.btnGuardarDecalog.Visibility = Windows.Visibility.Visible
            Dim dt As DataTable = negocio.ObtieneDistNoEnviada(idPSResumenD)
            Dim registroTotal = dt.NewRow()
            registroTotal("FONDO") = "TOTAL"
            For indexCol As Integer = 1 To dt.Columns.Count() - 1
                registroTotal(indexCol) = "0"
            Next
            Dim colGrayList As List(Of Integer) = New List(Of Integer)
            Dim colGray As Integer
            Dim acum As Double
            Dim rec As Double
            Dim total As Double
            For indexCol As Integer = 1 To dt.Columns.Count() - 3
                For indexRow As Integer = 0 To dt.Rows.Count() - 1
                    acum = Convert.ToDouble(registroTotal(indexCol).ToString().Replace(",",""))
                    rec = Convert.ToDouble(dt.Rows(indexRow).Item(indexCol).ToString().Replace(",",""))
                    total = acum + rec
                    registroTotal(indexCol) = total.ToString("#,##0.00")
                    Dim col = indexCol
                    If rec <> 0 And colGrayList.Find(Function(x) x = col) = 0 And colGray <> col
                        colGray = col
                        
                        If ObtieneEstatusEnvioDecalog(Convert.ToInt32(dt.Rows(indexRow).Item(dt.Columns.Count() - 2).ToString()), Convert.ToInt32(dt.Rows(indexRow).Item(dt.Columns.Count() - 1).ToString())) Then
                            colGrayList.Add(colGray)
                        End If
                        
                        
                    End If
                Next
                
            Next
            dt.Rows.Add(registroTotal)
            Dim view = New DataView(dt)
            Me.grdOrdenesDecalog.ItemsSource = view
            If Me.grdOrdenesDecalog.Columns.Count() > 0 Then
                Me.grdOrdenesDecalog.Columns(Me.grdOrdenesDecalog.Columns.Count() - 1).Width = 2
                Me.grdOrdenesDecalog.Columns(Me.grdOrdenesDecalog.Columns.Count() - 2).Width = 2
                Me.grdOrdenesDecalog.Columns(Me.grdOrdenesDecalog.Columns.Count() - 1).Visibility = Windows.Visibility.Hidden
                Me.grdOrdenesDecalog.Columns(Me.grdOrdenesDecalog.Columns.Count() - 2).Visibility = Windows.Visibility.Hidden
                Me.grdOrdenesDecalog.Visibility = System.Windows.Visibility.Visible
                Me.grdOrdenesDecalog.UpdateLayout()
                'Color Total
                Dim fila = Me.grdOrdenesDecalog.Items.Count() - 1
                For index As Integer = 0 To (Me.grdOrdenesDecalog.Columns.Count() - 3)
                    Dim celdaTotal As DataGridCell = getCell(fila, index, Me.grdOrdenesDecalog)
                    celdaTotal.Background = Brushes.DarkBlue
                    celdaTotal.Foreground = Brushes.White
                    celdaTotal.BorderBrush = Brushes.DarkBlue
                    celdaTotal.FontWeight = FontWeights.Bold
                    Dim colin = index
                    If colGrayList.Find(Function(x) x = colin) <> 0 Then
                        For indexRow As Integer = 0 To dt.Rows.Count() - 2
                            celdaTotal = getCell(indexRow, index, Me.grdOrdenesDecalog)
                            celdaTotal.Background = Brushes.LightGray
                            celdaTotal.BorderBrush = Brushes.LightGray
                            'celdaTotal.FontWeight = FontWeights.Bold
                        Next
                    End If
                    
                Next

                

            End If
            
            
            Mouse.OverrideCursor = Nothing
        End If
        

    End Sub

    Private Sub grdOrdenes_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
        e.Handled = True
        idPEJResumenF = New List(Of Integer)
        Me.grdOrdenes.UnselectAllCells()
    End Sub

    Private Sub grdOrdenes_HeaderSelect(ByVal sender As Object, ByVal e As DataGridSortingEventArgs)
        e.Handled = True
        Dim colclick As DataGridTextColumn = e.Column
        If colclick.DisplayIndex <> 0 Then
            If Not(Keyboard.IsKeyDown(Key.LeftCtrl) or Keyboard.IsKeyDown(Key.RightCtrl)) Then
                Me.grdOrdenes.UnselectAllCells()
                idPEJResumenF = New List(Of Integer)
            End If
        

            For index As Integer = 0 To (Me.grdOrdenes.Items.Count() - 1)
                Dim celdacol As DataGridCell = getCell(index, colclick.DisplayIndex, Me.grdOrdenes)
                celdacol.IsSelected = True
            
                Dim lst = Me.grdOrdenes.ItemsSource
                Dim dr As DataRowView = lst(index)
                If dr.Row.Item(colclick.DisplayIndex).ToString() <> "" and index <> (Me.grdOrdenes.Items.Count() - 1) Then
                    Dim valor = Convert.ToInt32(dr.Row.Item(Me.grdOrdenes.Columns.Count() - 1).ToString())
                    If idPEJResumenF.Find(Function(x) x = valor) = 0 Then
                        idPEJResumenF.Add(valor)
                    End If
                
                End If

            Next
        End If
        
     
    End Sub

    Private Sub grdOrdenesDecalog_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs)
        e.Handled = True
        idPEJResumenD = New List(Of Integer)
        idSecResumenD = New List(Of Integer)
        Me.grdOrdenesDecalog.UnselectAllCells()
    End Sub

    Private Sub grdOrdenesDecalog_HeaderSelect(ByVal sender As Object, ByVal e As DataGridSortingEventArgs)
        e.Handled = True
        Dim colclick As DataGridTextColumn = e.Column
        If colclick.DisplayIndex <> 0 Then
            Dim partida = BSO.LstPS.Find(Function(x) x.PartidaSolId = idPSResumenD)

            'If (partida.TvngId > 4) Then
            '    Me.grdOrdenesDecalog.UnselectAllCells()
            '    idPEJResumenD = New List(Of Integer)
            '    idSecResumenD = New List(Of Integer)
            'End If

            If Not(Keyboard.IsKeyDown(Key.LeftCtrl) or Keyboard.IsKeyDown(Key.RightCtrl)) Then
                Me.grdOrdenesDecalog.UnselectAllCells()
                idPEJResumenD = New List(Of Integer)
                idSecResumenD = New List(Of Integer)
            End If
        

            For index As Integer = 0 To (Me.grdOrdenesDecalog.Items.Count() - 1)
                Dim celdacol As DataGridCell = getCell(index, colclick.DisplayIndex, Me.grdOrdenesDecalog)
                celdacol.IsSelected = True

            
                Dim lst = Me.grdOrdenesDecalog.ItemsSource
                Dim dr As DataRowView = lst(index)
                If dr.Row.Item(colclick.DisplayIndex).ToString() <> "0.00" and index <> (Me.grdOrdenesDecalog.Items.Count() - 1) Then
                    Dim valorSec = Convert.ToInt32(dr.Row.Item(Me.grdOrdenesDecalog.Columns.Count() - 1).ToString())
                    Dim valorID = Convert.ToInt32(dr.Row.Item(Me.grdOrdenesDecalog.Columns.Count() - 2).ToString())
                    Dim found As Boolean = False
                    For i As Integer = 0 To (idPEJResumenD.Count() - 1)
                        If idPEJResumenD(i) = valorID and idSecResumenD(i) = valorSec Then
                            found = True
                            Exit For
                        End If
                    Next
                    If Not found Then
                        idPEJResumenD.Add(valorID)
                        idSecResumenD.Add(valorSec)
                    End If

                
                End If

            Next
        End If
        
     
    End Sub


    Public Function getCell(ByVal row As Integer, ByVal column As Integer, ByRef dg As DataGrid) As DataGridCell
        Dim rowContainer As DataGridRow = dg.ItemContainerGenerator.ContainerFromIndex(row)
        Dim presenter As DataGridCellsPresenter = GetVisualChild(Of DataGridCellsPresenter)(rowContainer)

        Dim cell As DataGridCell = DirectCast(presenter.ItemContainerGenerator.ContainerFromIndex(column), DataGridCell)
        If cell Is Nothing Then
            dg.ScrollIntoView(rowContainer, dg.Columns(column))
            cell = DirectCast(presenter.ItemContainerGenerator.ContainerFromIndex(column), DataGridCell)
        End If
        Return cell
    End Function

    Public Overloads Function GetVisualChild(Of T As Visual)(ByVal parent As Visual) As T
        Dim child As T = Nothing
        Dim numVisuals As Integer = VisualTreeHelper.GetChildrenCount(parent)
        For i As Integer = 0 To numVisuals - 1
            Dim v As Visual = DirectCast(VisualTreeHelper.GetChild(parent, i), Visual)
            child = TryCast(v, T)
            If child Is Nothing Then
                child = GetVisualChild(Of T)(v)
            End If
            If child IsNot Nothing Then
                Exit For
            End If
        Next
        Return child
    End Function

    Private Sub btnReporteLiquidez_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnReporteLiquidez.Click
        Mouse.OverrideCursor = Cursors.Wait
        Dim sMsgError As String = ""
        Dim reporteStatus As Boolean = True
        If Not chkFondos.IsChecked And Not chkPorvenir.IsChecked Then
            Mouse.OverrideCursor = Nothing
            MessageBox.Show("Debe seleccionar al menos un tipo de reporte.", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Information)
            Exit Sub
        End If
        Try
            Dim dialog As New Microsoft.Win32.SaveFileDialog()
            dialog.FileName = "Selecciona Directorio"
            dialog.ValidateNames = False
            dialog.CheckFileExists = False
            dialog.CheckPathExists = True
            If dialog.ShowDialog() Then
                Mouse.OverrideCursor = Cursors.Wait
                Dim ruta = dialog.FileName
                Dim rutaAux() As String = ruta.Split("\")
                ruta = ruta.Replace(rutaAux(rutaAux.Count - 1), "")
                If chkFondos.IsChecked Then
                    sMsgError = ""
                    If Not servicioMonitor.ExportarReporteLiqExcel("FONDOS", BSO.FecOperacion, ruta, sMsgError) Then
                        reporteStatus = False
                        MessageBox.Show("Error TI500. Error al generar Reporte de Liquidez (Fondos de Iversión): " & sMsgError, tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Error)
                    End If

                End If
                If chkPorvenir.IsChecked Then
                    sMsgError = ""
                    If Not servicioMonitor.ExportarReporteLiqExcel("PORVENIR", BSO.FecOperacion, ruta, sMsgError) Then
                        reporteStatus = False
                        MessageBox.Show("Error TI500. Error al generar Reporte de Liquidez (Porvenir): " & sMsgError, tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Error)
                    End If

                End If
                If reporteStatus Then
                    MessageBox.Show("Operación Exitosa", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Information)
                End If
            End If
        Catch ex As Exception
            Mouse.OverrideCursor = Nothing
            MessageBox.Show("Error TI500. Error al generar Reporte de Liquidez: " & ex.Message, tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Error)
        End Try
        Mouse.OverrideCursor = Nothing

    End Sub

    Private Sub btnGuardarFrida_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnGuardarFrida.Click
        Dim listInterm As List(Of CTDistribLiqReduc) = New List(Of CTDistribLiqReduc)
        Dim mensaje As System.Text.StringBuilder = New System.Text.StringBuilder("")
        Mouse.OverrideCursor = Cursors.Wait
        If MessageBox.Show("¿Desea guardar los valores de distribución en Frida?", tituloMensaje, MessageBoxButton.YesNo, MessageBoxImage.Question) = MessageBoxResult.Yes Then
            Dim eventoBit = CBitacoraFRIDA.GenerarEvento(CBitacoraFRIDA.CveEventosBit.GUARDAR_ORDEN_FRIDA, CServiciosMacrosSyBaseDB.IDUSUARIO, "FLDistFondoInterRepo.xaml -> btnGuardarFrida")
            If idPEJResumenF.Count() = 0 Then

                Dim PsAux = BSO.LstPS.Find(Function(x) x.PartidaSolId = idPSResumenF)
                Dim list = Me.grdOrdenes.ItemsSource
                For Each dr As DataRowView In list
                    If Not dr.Row.Item(0).ToString().Equals("TOTAL") Then
                        If Not dr.Row.Item(Me.grdOrdenes.Columns.Count() - 1).ToString().Equals("") Then
                            Dim valor = Convert.ToInt32(dr.Row.Item(Me.grdOrdenes.Columns.Count() - 1).ToString())
                            If idPEJResumenF.Find(Function(x) x = valor) = 0 Then
                                idPEJResumenF.Add(valor)
                                Dim intermediario = lstDistribTotal.Find(Function(x) x.IdPs = idPSResumenF And x.IdPEJ = valor)
                                Dim sMsgError As String = ""
                                eventoBit.GuadarDetalle("idPEJ", intermediario.IdPEJ)
                                Dim resultado = GuardarFrida(intermediario, PsAux, sMsgError)
                                If resultado = CSGeneralDistribLiq.ESTADOTRANSDISTRIB.INFO_ALMACENADA_FRIDA Then
                                    listInterm.Add(intermediario)
                                    'EliminarDistribucion(intermediario)
                                Else
                                    Dim errorBit = eventoBit.GuardarError("Error al guardar orden en FRIDA PEJ:" & intermediario.IdPEJ.ToString & " - " & sMsgError)
                                    mensaje.Append(sMsgError & " Estado: " & resultado & " -Codigo:" & errorBit.IdError)
                                    mensaje.AppendLine()
                                End If
                            End If
                        End If
                    End If

                Next
                If listInterm.Count > 0 Then
                    EliminarDistribuciones(listInterm)
                End If
                eventoBit.ActualizarFechaFinDelEvento()
                servicioGenerales.RegistrarNotificacion("Resumen Distribucion Liq - Se guarda partidas FRIDA")
                If mensaje.ToString().Length = 0 Then
                    MessageBox.Show("Operación Exitosa", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Information)
                Else
                    MessageBox.Show("Error TI500. Error al guardar en frida: " & vbCrLf & mensaje.ToString(), tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Error)
                End If
                idPEJResumenF = New List(Of Integer)
            Else
                Dim PsAux = BSO.LstPS.Find(Function(x) x.PartidaSolId = idPSResumenF)
                For Each idPEJ As Integer In idPEJResumenF
                    Dim sMsgError As String = ""
                    Dim id As Integer = idPEJ
                    Dim intermediario = lstDistribTotal.Find(Function(x) x.IdPs = idPSResumenF And x.IdPEJ = id)
                    eventoBit.GuadarDetalle("idPEJ", intermediario.IdPEJ)
                    Dim resultado = GuardarFrida(intermediario, PsAux, sMsgError)
                    If resultado = CSGeneralDistribLiq.ESTADOTRANSDISTRIB.INFO_ALMACENADA_FRIDA Then
                        'EliminarDistribucion(intermediario)
                        listInterm.Add(intermediario)
                    Else
                        Dim errorBit = eventoBit.GuardarError("Error al guardar orden en FRIDA PEJ:" & intermediario.IdPEJ.ToString & " - " & sMsgError)
                        mensaje.Append(sMsgError & " Estado: " & resultado & " -Codigo:" & errorBit.IdError)
                        mensaje.AppendLine()
                    End If
                Next
                If listInterm.Count > 0 Then
                    EliminarDistribuciones(listInterm)
                End If
                eventoBit.ActualizarFechaFinDelEvento()
                servicioGenerales.RegistrarNotificacion("Resumen Distribucion Liq - Se guarda partidas FRIDA")
                If mensaje.ToString().Length = 0 Then
                    MessageBox.Show("Operación Exitosa", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Information)
                Else
                    MessageBox.Show("Error TI500. Error al guardar en frida: " & vbCrLf & mensaje.ToString(), tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Error)
                End If
            End If

        End If
        Mouse.OverrideCursor = Nothing
    End Sub

    Private Sub btnModificarDist_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnModificarDist.Click
        Mouse.OverrideCursor = Cursors.Wait
        Dim valido = ValidarDistResumen()
        If valido Then
            Me.tcLiquidez.SelectedIndex = 0
            Me.tcLiquidez.SelectedItem = Me.tabDistribucionLiquidez
            Me.tabDistribucionLiquidez.IsSelected = True

            ActualizarPantallaDistribLiq()
            btnRefreshPSLiberadas_Click(Me.btnRefreshPSLiberadas, Nothing)

            Dim partida As CTPartidaSolicitud = BSO.LstPS.Find(Function(x) x.PartidaSolId = idPSResumenF)

            Me.grdPSDistribLiq.SelectedItem = partida

            Me.cmbDistribInter.SelectedItem = partida.LstPEJ.Find(Function(x) x.PartidaEJId = idPEJResumenF(0))

        End If
        Mouse.OverrideCursor = Nothing
    End Sub

    Private Sub btnEliminarDist_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnEliminarDist.Click
        Mouse.OverrideCursor = Cursors.Wait
        Dim valido = ValidarDistResumen()
        If valido Then
            If MessageBox.Show ("¿Desea eliminar los valores de distribución?", tituloMensaje, MessageBoxButton.YesNo, MessageBoxImage.Question)  = MessageBoxResult.Yes Then
                Dim distribucion As CTDistribLiqReduc = lstDistribTotal.Find(Function(x) x.IdPs = idPSResumenF and x.IdPEJ = idPEJResumenF(0))
                Dim idPs = idPSResumenF
                EliminarDistribucion(distribucion)
                Dim list = Me.grdResumendDist.ItemsSource
                If list isNot Nothing Then
                    For Each seleccion As CTPartidaSolicitud In list
                        If seleccion.PartidaSolId = idPs Then
                            Me.grdResumendDist.SelectedItem = seleccion
                            Exit For
                        End If
                    Next

                End If
            End If
        End If
        Mouse.OverrideCursor = Nothing
    End Sub

    Private Sub btnGuardarDecalog_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnGuardarDecalog.Click
        Dim mensaje As System.Text.StringBuilder = New System.Text.StringBuilder("")
        Mouse.OverrideCursor = Cursors.Wait
        Dim valido = ValidarOrdenes()
        If valido Then
            'Dim cadena As String = ValidarEnviadas()
            If MessageBox.Show ("¿Desea generar ordenes a los valores de distribución en Decalog?", tituloMensaje, MessageBoxButton.YesNo, MessageBoxImage.Question)  = MessageBoxResult.Yes Then
                Dim eventoBit = CBitacoraFRIDA.GenerarEvento(CBitacoraFRIDA.CveEventosBit.GUARDAR_ORDEN_DECALOG, CServiciosMacrosSyBaseDB.IDUSUARIO, "FLDistFondoInterRepo.xaml -> btnGuardarDecalog")
                If idPEJResumenD.Count() = 0 Then
                
                    Dim PsAux = BSO.LstPS.Find(Function(x) x.PartidaSolId = idPSResumenD)
                    Dim list = Me.grdOrdenesDecalog.ItemsSource
                    For Each dr As DataRowView In list
                        If Not dr.Row.Item(0).ToString().Equals("TOTAL") Then
                            If dr.Row.Item(Me.grdOrdenesDecalog.Columns.Count() - 2).ToString() <> ""  Then
                                Dim valorId = Convert.ToInt32(dr.Row.Item(Me.grdOrdenesDecalog.Columns.Count() - 2).ToString())
                                Dim valorSec = Convert.ToInt32(dr.Row.Item(Me.grdOrdenesDecalog.Columns.Count() - 1).ToString())
                                If idPEJResumenD.Find(Function(x) x = valorId) = 0 Then
                                    idPEJResumenD.Add(valorId)
                                    Dim sMsgError As String = ""
                                    Dim resultado = GenerarOrdenes(valorId, valorSec, PsAux, sMsgError, eventoBit)
                                    'If Not resultado = CSGeneralDistribLiq.ESTADOTRANSDISTRIB.ENVIADA_A_DECALOG Then
                                        'mensaje.Append(sMsgError & " Estado: " & resultado)
                                        'mensaje.AppendLine()
                                    'End If
                                End If
                            End If
                        End If
                    
                    Next
                    eventoBit.ActualizarFechaFinDelEvento()
                    servicioGenerales.RegistrarNotificacion("Resumen Distribucion Liq - Se guarda partidas DECALOG")
                    
                    If mensaje.ToString().Length = 0 Then
                        Try
                            Dim mensajeCierre = negocio.MensajeValidacionCierrePS(PsAux.PartidaSolId)
                            If Not mensajeCierre.Length > 0 Then
                                BSO.CerrarPS(PsAux, Me.txtComentarios.Text.ToString().Trim())
                            End If
                            MessageBox.Show("Operación Exitosa" , tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Information)
                        Catch ex As Exception
                            MessageBox.Show("Error TI500. Error al cerrar ps en decalog: " & vbCrLf & mensaje.ToString(), tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Error)
                        End Try
                        
                    Else
                        MessageBox.Show("Error TI500. Error al generar orden en decalog: " & vbCrLf & mensaje.ToString(), tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Error)
                    End If
                    ActualizaExps()
                    idPEJResumenD = New List(Of Integer)
                Else
                    Dim PsAux = BSO.LstPS.Find(Function(x) x.PartidaSolId = idPSResumenD)
                    For index As Integer = 0 To (idPEJResumenD.Count() - 1)

                        Dim sMsgError As String = ""

                        Dim resultado = GenerarOrdenes(idPEJResumenD(index), idSecResumenD(index), PsAux, sMsgError, eventoBit)
                        'If Not resultado = CSGeneralDistribLiq.ESTADOTRANSDISTRIB.ENVIADA_A_DECALOG Then
                            'mensaje.Append(sMsgError & " Estado: " & resultado)
                            'mensaje.AppendLine()
                        'End If
                    Next
                    eventoBit.ActualizarFechaFinDelEvento()
                    servicioGenerales.RegistrarNotificacion("Resumen Distribucion Liq - Se guarda partidas DECALOG")
                    idPEJResumenD = New List(Of Integer)
                    idSecResumenD = New List(Of Integer)
                    If mensaje.ToString().Length = 0 Then
                         Try
                            Dim mensajeCierre = negocio.MensajeValidacionCierrePS(PsAux.PartidaSolId)
                            If Not mensajeCierre.Length > 0 Then
                                BSO.CerrarPS(PsAux, Me.txtComentarios.Text.ToString().Trim())
                            End If
                            MessageBox.Show("Operación Exitosa" , tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Information)
                        Catch ex As Exception
                            MessageBox.Show("Error TI500. Error al cerrar ps en decalog: " & vbCrLf & mensaje.ToString(), tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Error)
                        End Try
                        'MessageBox.Show("Operación Exitosa" , tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Information)
                    Else
                        MessageBox.Show("Error TI500. Error al generar orden en decalog: " & vbCrLf & mensaje.ToString(), tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Error)
                    End If    
                    ActualizaExps()
                End If
            
            End If
        End If
        Mouse.OverrideCursor = Nothing

    End Sub

    Private Function ValidarEnviadas() As String
        Dim cadena As String = ""
        Dim partida As CTPartidaSolicitud = BSO.LstPS.Find(Function(x) x.PartidaSolId = idPSResumenD)

        If partida.TvngId > 4 Then
            If ObtieneEstatusEnvioDecalog(idPEJResumenD(0), idSecResumenD(0)) Then
                cadena = "Este valor de distribución ya fue enviado anteriormente a Decalog. "
            End If
        Else
            If idPEJResumenD.Count() = 0 Then
                'If ObtieneEstatusEnvioDecalogPS(idPSResumenD) Then
                '    cadena = "Existe valores de distribución que ya fueron enviados anteriormente a Decalog. "
                'End If

                Dim list = Me.grdOrdenesDecalog.ItemsSource
                For Each dr As DataRowView In list
                    If Not dr.Row.Item(0).ToString().Equals("TOTAL") Then
                        If dr.Row.Item(Me.grdOrdenesDecalog.Columns.Count() - 2).ToString() <> ""  Then
                            Dim valorId = Convert.ToInt32(dr.Row.Item(Me.grdOrdenesDecalog.Columns.Count() - 2).ToString())
                            Dim valorSec = Convert.ToInt32(dr.Row.Item(Me.grdOrdenesDecalog.Columns.Count() - 1).ToString())
                            If ObtieneEstatusEnvioDecalog(valorId, valorSec) Then
                                cadena = "Existe valores de distribución que ya fueron enviados anteriormente a Decalog. "
                                Exit For
                            End If
                        End If
                    End If
                Next
                        
                            
                                


            Else
                For index As Integer = 0 To idPEJResumenD.Count() - 1
                    If ObtieneEstatusEnvioDecalog(idPEJResumenD(index), idSecResumenD(index)) Then
                        cadena = "Existe valores de distribución que ya fueron enviados anteriormente a Decalog. "
                        Exit For
                    End If
                Next
            End If
        End If
        
        Return cadena
    End Function

    Private Function ValidarOrdenes() As Boolean
        Dim valido As Boolean = True
        NumInstrumento = 0

        Dim partida As CTPartidaSolicitud = BSO.LstPS.Find(Function(x) x.PartidaSolId = idPSResumenD)

        If partida.TvngId > 4 Then

            'If idPEJResumenD.Count() = 0 or idSecResumenD.Count() = 0 Then
            '    valido = False
            '    MessageBox.Show("No existen valores de distribución seleccionados", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Exclamation)
            'End If

            'If idPEJResumenD.Count() > 1 or idSecResumenD.Count() > 1 Then
            '    valido = False
            '    MessageBox.Show("Solo debe seleccionarse un intermediario a la vez", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Exclamation)
            'End If

            If valido and Me.txtInstrumento.Text.ToString().Trim().Equals("") Then
                valido = False
                MessageBox.Show("Debe introducirse un instrumento para generar la orden", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Exclamation)
            End If

            Me.txtInstrumento.Text = Me.txtInstrumento.Text.ToString().ToUpper()

            Dim mensaje As String = ""
            If valido and Not negocio.ValidaInstrumento(Me.txtInstrumento.Text.ToString().Trim(), NumInstrumento, mensaje) Then
                valido = False
                MessageBox.Show(mensaje, tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Exclamation)
            End If
        End If
        
        Return valido
    End Function

    Private Function ValidarDistResumen() As Boolean
        Dim valido As Boolean = True
        If idPEJResumenF.Count() = 0 Then
            valido = False
            MessageBox.Show("No existen valores de distribución seleccionados", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Exclamation)
        End If

        If idPEJResumenF.Count() > 1 Then
            valido = False
            MessageBox.Show("Solo debe seleccionarse un intermediario tasa", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Exclamation)
        End If

        Return valido
    End Function

    Private Function GuardarFrida(ByRef intermediario As CTDistribLiqReduc, ByRef PsAux As CTPartidaSolicitud, ByRef sMsgError As String) As CSGeneralDistribLiq.ESTADOTRANSDISTRIB
        Dim resultado = negocio.GuardarFondeoReportosXIntermediario(intermediario, PsAux, sMsgError)
        Return resultado
    End Function

    Private Function GenerarOrdenes(ByVal idPej As Integer, ByVal Sec As Integer, ByRef PsAux As CTPartidaSolicitud, ByRef sMsgError As String, ByRef eventoBit As CSBitEvento) As CSGeneralDistribLiq.ESTADOTRANSDISTRIB
        Dim SecuenciaArchivo As String = "PEJ" & idPej.ToString() & "SEC" & Sec.ToString()
        Dim resultado As CSGeneralDistribLiq.ESTADOTRANSDISTRIB   ' Variable para almacenar temporalmente el estado de la transacción. 
        Dim archivo As String = ""
        Dim intermediario = GenerarObjeto(idPej, Sec)
        If PsAux.TvngId > 4
            eventoBit.GuadarDetalle("RV idPej", idPej)
            eventoBit.GuadarDetalle("RV Sec", Sec)
            resultado = negocio.FondeoBancariosXIntermediario(intermediario, PsAux, NumInstrumento, archivo, SecuenciaArchivo, sMsgError, eventoBit)
        Else
            eventoBit.GuadarDetalle("RF idPej", idPej)
            eventoBit.GuadarDetalle("RF Sec", Sec)
            resultado = negocio.FondeoReportosXIntermediario(intermediario, PsAux, archivo, SecuenciaArchivo, sMsgError, eventoBit)
        End If

        'zIf resultado = CSGeneralDistribLiq.ESTADOTRANSDISTRIB.ENVIADA_A_DECALOG Then
            Dim mensaje As String = ""
            Dim index = archivo.IndexOf(".tl")
            If index > 0 Then
                archivo = archivo.Substring(0,index)
            End If
            If Not negocio.ActualizaArchivoEstatusDecalog(idPej, Sec, archivo, mensaje) Then
                Dim errorBit = eventoBit.GuardarError("Error al actualizar Estatis Envio: " & mensaje)
                MessageBox.Show("Ocurrió un error al actualizar estatus de envío " & mensaje & " -Codigo:" & errorBit.IdError, tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Error)
            End If
        'zEnd If

        Return resultado
    End Function

    Private Function GenerarObjeto(ByVal IdPej As Integer, ByVal sec As Integer) As CTDistribLiqReduc
        Dim intermediario As CTDistribLiqReduc = New CTDistribLiqReduc(idPSResumenD, idPEj)
        Dim dis As CTDistribLiqReduc.structDistribFondoXInter
        Dim list = Me.grdOrdenesDecalog.ItemsSource
        For Each dr As DataRowView In list
            Dim valorId = Convert.ToInt32(dr.Row.Item(Me.grdOrdenesDecalog.Columns.Count() - 2).ToString())
            Dim valorSec = Convert.ToInt32(dr.Row.Item(Me.grdOrdenesDecalog.Columns.Count() - 1).ToString())
            If valorId = IdPej and valorSec = sec Then
                For index As Integer = 1 To Me.grdOrdenesDecalog.Columns.Count() - 3
                    If Not Convert.ToString(dr.Row.Item(index).ToString()).Equals("0.00") and Not Convert.ToString(dr.Row.Item(0).ToString()).Equals("TOTAL") Then
                        dis = New CTDistribLiqReduc.structDistribFondoXInter()
                        dis.CodFondo = Convert.ToString(dr.Row.Item(0).ToString())
                        dis.MontoDistrib = Convert.ToDouble(Convert.ToString(dr.Row.Item(index).ToString()))
                        intermediario.LstDistrib.Add(dis)
                    End If
                Next
                
            End If
        Next
     
                            
                            
        Return intermediario
    End Function

    Private Sub EliminarDistribuciones(ByRef distribucion As List(Of CTDistribLiqReduc))
        For Each interm As CTDistribLiqReduc In distribucion
            EliminarDistribucion(interm)
        Next
        ActualizaExps()
    End Sub

    Private Sub EliminarDistribucion(ByRef distribucion As CTDistribLiqReduc)
        'Se recalculan los saldos estimados por fondo, según todo lo distribuido 
        lstDistribTotal.Remove(distribucion)

        SaldoEstimado.LstDistrib.Clear()
        For Each distrib As CTDistribLiqReduc In lstDistribTotal

            Dim fondosMontos = distrib.LstDistrib.FindAll(Function(x) x.MontoDistrib <> 0)
            For Each fondomonto As CTDistribLiqReduc.structDistribFondoXInter In fondosMontos
                Dim structFondoInter = New CTDistribLiqReduc.structDistribFondoXInter()
                structFondoInter.CodFondo = fondomonto.CodFondo
                structFondoInter.MontoDistrib = fondomonto.MontoDistrib
                SaldoEstimado.LstDistrib.Add(structFondoInter)
            Next

        Next
        
        'InicioTabResumenDist()
        'ActualizaExps()
    End Sub

    Private Function ObtieneEstatusEnvioDecalog(ByVal idPej As Integer, ByVal sec As Integer) As Boolean
        Return negocio.ObtieneEstatusEnvioDecalog(idPej, sec)
    End Function
    
    Private Function ObtieneEstatusEnvioDecalogPS(ByVal idPs As Integer) As Boolean
        Return negocio.ObtieneEstatusEnvioDecalogPS(idPs)
    End Function

#End Region


#Region "TAB CIERRE SOLICITUDES"
    Private Sub InicioTabCierreSolicitudes()
        Me.txtFechaBSOCierre.Text = BSO.FecOperacion.ToString("dd/MM/yyyy")
        lstDataPartida = New List(Of CTPartidaSolicitud)()
        lstDataPartida = BSO.LstPS.FindAll(Function(x) x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.LIBERADA or x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.EN_DISTRIBUCION)
        lstDataPartida = lstDataPartida.OrderBy(Function(x) x.PartidaSolId).ToList()
        Dim lstPartidasOC = New ObservableCollection(Of CTPartidaSolicitud)(lstDataPartida)
        Me.grdPartidasCierre.ItemsSource = lstPartidasOC

    End Sub

    Private Sub CheckBox_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim currentCheck As CheckBox = TryCast(sender, CheckBox)
        Dim partidaclick As CTPartidaSolicitud = TryCast(currentCheck.DataContext, CTPartidaSolicitud)
        For Each partida As CTPartidaSolicitud In lstDataPartida
            If partida.PartidaSolId <> partidaclick.PartidaSolId Then
                partida.SeleccionSol = False
            Else
                partida.SeleccionSol = partidaclick.SeleccionSol
            End If
        Next
        lstDataPartida = lstDataPartida.OrderBy(Function(x) x.PartidaSolId).ToList()
        Dim lstPartidasOC = New ObservableCollection(Of CTPartidaSolicitud)(lstDataPartida)
        Me.grdPartidasCierre.ItemsSource = lstPartidasOC
    End Sub

    Private Sub btnCierreSolicitud_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnCierreSolicitud.Click
        Mouse.OverrideCursor = Cursors.Wait
        Try
            If ValidarSeleccionPS() Then
                ActualizaFoliosDecalog()
                Dim lst = Me.grdPartidasCierre.ItemsSource
                For Each partida As CTPartidaSolicitud In lst
                    If partida.SeleccionSol = True Then
                        Dim incompleta = MensajeValidacion(partida)
                        If MessageBox.Show ("¿Desea cerrar las partidas de solicitud seleccionadas?", tituloMensaje, MessageBoxButton.YesNo, MessageBoxImage.Question)  = MessageBoxResult.Yes Then
                            Dim eventoBit = CBitacoraFRIDA.GenerarEvento(CBitacoraFRIDA.CveEventosBit.CANCELAR_PS, CServiciosMacrosSyBaseDB.IDUSUARIO, "FLDistFondoInterRepo.xaml -> btnCierreSolicitud")
                            CerrarPs(partida, incompleta, Nothing)
                            servicioGenerales.RegistrarNotificacion("Cierre Partidas - Se cierra partida manual")
                            MessageBox.Show("Operación Exitosa" , tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Information)
                            Exit For
                        End If       
                    End If
                Next
                
            End If
        Catch ex As Exception
            Mouse.OverrideCursor = Nothing
            MessageBox.Show("Error TI500. Error al cerrar la partida de solicitud: " & ex.Message, tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Error)
        End Try
        Mouse.OverrideCursor = Nothing
    End Sub

    Private Sub CerrarPS(ByRef partida As CTPartidaSolicitud, ByVal incompleta As Boolean, ByRef eventoBit As CSBitEvento)
        If incompleta Then
            BSO.CerrarIncompletaPS(partida, Me.txtComentarios.Text.ToString().Trim(), eventoBit)
        Else
            BSO.CerrarPS(partida, Me.txtComentarios.Text.ToString().Trim())
        End If
        
    End Sub

    Private Function MensajeValidacion(ByRef partida As CTPartidaSolicitud) As Boolean
        Try
            Dim mensaje = negocio.MensajeValidacionCierrePS(partida.PartidaSolId)
            If mensaje.Length > 0 Then
                MessageBox.Show("Para la solicitud seleccionada." & vbCrLf & mensaje, tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Exclamation)
                Return True
            End If
            Return False
        Catch ex As Exception
            Return False
        End Try
        
    End Function

    Private Sub ActualizaFoliosDecalog()
        Try
            Dim mensaje As String = ""
            Dim fechaIni As String = BSO.FecOperacion.ToString("yyyy-MM-dd") & " 00:00:00"
            Dim fechaFin As String = BSO.FecOperacion.ToString("yyyy-MM-dd") & " 23:59:59"
            'xxx
            'negocio.RecuperarFoliosDecalog(fechaIni, fechaFin, mensaje)
        Catch ex As Exception
            Exit Sub
        End Try
         

    End Sub
        
    Private Function ValidarSeleccionPS() As Boolean

        Dim valido As Boolean = True
        Dim count As Integer = 0
        Dim lst = Me.grdPartidasCierre.ItemsSource
        For Each resumen As CTPartidaSolicitud In lst
            If resumen.SeleccionSol = True Then
                count = count + 1
            End If
        Next
        If count = 0 Then
            MessageBox.Show ("Debe seleccionar una partida de solicitud para cerrarla.", tituloMensaje, MessageBoxButton.OK, MessageBoxImage.Exclamation) 
            valido = False
        End If

       
        Return valido
    End Function


    
    
#End Region


#Region "TAB RECUPERACIÓN DE FOLIOS DECALOG"

 Private Sub InicializarFechaHora () 

        Me.fechaInicio.Text = Date.Now.ToString ("dd/MM/yyyy") 
        Me.tiempoInicio.txtHora.Text  = "00"
        Me.tiempoInicio.txtMinuto.Text = "00" 
        Me.tiempoInicio.txtSegundo.Text = "00" 

        Me.fechaFin.Text = Now.ToString ("dd/MM/yyyy") 
        Me.tiempoFin.txtHora.Text  = Date.Now.Hour.ToString("0#")   
        Me.tiempoFin.txtMinuto.Text = Date.Now.Minute.ToString ("0#") 
        Me.tiempoFin.txtSegundo.Text = "00" 


    End Sub

 Private Sub btnConsultar_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles btnConsultar.Click
        Dim sFechaIni As String 
        Dim sFechaFin As String 
        Dim sMsgError As String = ""


    Mouse.OverrideCursor = Cursors.Wait  

        Try        

          sFechaIni =   String.Format(Me.fechaInicio.Text,"yyyy-MM-dd") & " " & String.Format ( Me.tiempoInicio.HoraCompleta ,"HH:mm:ss")
          sFechaFin  =  String.Format(Me.fechaFin.Text,"yyyy-MM-dd") & " " & String.Format ( Me.tiempoFin.HoraCompleta ,"HH:mm:ss")

          
           If Convert.ToDateTime (sFechaFin) < Convert.ToDateTime (sFechaIni)  then 
              MessageBox.Show ("No se pudo obtener la información: la fecha fin debe ser mayor o igual a la fecha de inicio.", "Obtención de Folios Decalog ", MessageBoxButton.OK, MessageBoxImage.Exclamation)
              Mouse.OverrideCursor = Nothing
              Exit Sub 
           End If
                       
          grdFoliosRecdecalog.ItemsSource = negocio.ObtenerInfoEstatusRegGral (Convert.ToDateTime(sFechaIni), Convert.ToDateTime ( sFechaFin),sMsgError)                                                                             

          If Not sMsgError.Equals ("") then 
             MessageBox.Show ("No se pudo obtener la información debido a: " & sMsgError, "Obtención de Folios Decalog ", MessageBoxButton.OK, MessageBoxImage.Exclamation)
             Mouse.OverrideCursor = Nothing             
          End If

          grdFoliosRecdecalog.UpdateLayout ()

            
        Catch ex As Exception
            MessageBox.Show("No existe información para los criterios introducidos:" & ex.Message, "Obtención de Folios Decalog ", MessageBoxButton.OK, MessageBoxImage.Exclamation)            
        End Try

        Mouse.OverrideCursor = Nothing


End Sub

 Private Sub btnActRespDec_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles btnActRespDec.Click
    
        Dim sFechaIni As String 
        Dim sFechaFin As String 
        Dim sMsgError As String = ""

        
        Dim eventoBit = CBitacoraFRIDA.GenerarEvento (CBitacoraFRIDA.CveEventosBit.RECUPERAR_FOLIO_DECALOG,CServiciosMacrosSyBaseDB.IDUSUARIO) 


    Mouse.OverrideCursor = Cursors.Wait  

        Try        

          sFechaIni =   String.Format(Me.fechaInicio.Text,"yyyy-MM-dd") & " " & String.Format ( Me.tiempoInicio.HoraCompleta ,"HH:mm:ss")
          sFechaFin  =  String.Format(Me.fechaFin.Text,"yyyy-MM-dd") & " " & String.Format ( Me.tiempoFin.HoraCompleta ,"HH:mm:ss")

          eventoBit.GuadarDetalle ("PARAM_FECHA_INI",sFechaIni ) 
          eventoBit.GuadarDetalle ("PARAM_FECHA_FIN",sFechaFin ) 



           If Convert.ToDateTime (sFechaFin) < Convert.ToDateTime (sFechaIni)  then 
              MessageBox.Show ("No se pudo obtener la información: la fecha fin debe ser mayor o igual a la fecha de inicio.", "Obtención de Folios Decalog ", MessageBoxButton.OK, MessageBoxImage.Exclamation)
              Mouse.OverrideCursor = Nothing
              Exit Sub 
           End If
                       

          If  negocio.RecuperarFoliosDecalog (sFechaIni,sFechaFin,sMsgError,eventoBit) = false then           
              MessageBox.Show ("Ocurrió un error en la recuperación de los folios Decalog: " & "Id Evento: " & eventoBit.IdRegistro   , "Obtención de Folios Decalog ", MessageBoxButton.OK, MessageBoxImage.Error )                 

          else
              MessageBox.Show ("Proceso terminado.", "Obtención de Folios Decalog ", MessageBoxButton.OK, MessageBoxImage.Information)                 
          End If

          eventoBit.ActualizarFechaFinDelEvento ()

          grdFoliosRecdecalog.ItemsSource = negocio.ObtenerInfoEstatusRegGral (Convert.ToDateTime(sFechaIni), Convert.ToDateTime ( sFechaFin),sMsgError)                                                                             

          If Not sMsgError.Equals ("") then 
             MessageBox.Show ("No se pudo obtener la información, dé click en el botón de lupa para cargar los datos en el periodo específicado.", "Obtención de Folios Decalog ", MessageBoxButton.OK, MessageBoxImage.Exclamation)
             Mouse.OverrideCursor = Nothing             
          End If

          grdFoliosRecdecalog.UpdateLayout ()

            
        Catch ex As Exception
            MessageBox.Show("No existe información para los criterios introducidos:" & ex.Message, "Obtención de Folios Decalog ", MessageBoxButton.OK, MessageBoxImage.Exclamation)            
        End Try

        Mouse.OverrideCursor = Nothing





 End Sub


 

 Private Sub btnLimpiar_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles btnLimpiar.Click
 
     InicializarFechaHora ()
     grdFoliosRecdecalog.ItemsSource = Nothing 
     grdFoliosRecdecalog.UpdateLayout ()
 
 End Sub

#End Region


#Region "CONSULTA DE SALDOS"

Private Sub cmbTVNGDistrib_SelectionChanged(ByVal sender As System.Object , ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles cmbTVNGDistrib.SelectionChanged
Dim sMsgError           As String = ""
Dim idTVNG              as Integer
Dim lstFondos           As List(Of String )
Dim distribEnTrabajo    As CTDistribLiqReduc
dim lstSaldosDistrib    As List(Of CTFondosDistribLiq)

  Mouse.OverrideCursor = Cursors.Wait  


  Dim eventoBit =  CBitacoraFRIDA.GenerarEvento (CBitacoraFRIDA.CveEventosBit.CONSULTA_SALDOS_X_TVNG,CServiciosMacrosSyBaseDB.IDUSUARIO,"FLDistEnPEJ->cmbTVNGDistrib_SelectionChanged o btnRefreshSelTVNG_Click")    

  If e.AddedItems.Count = 1 then 

        idTVNG    = Convert.ToInt16( e.AddedItems (0).Clave)    
        lstFondos =   negocio.ObtenerFondosTVNG (idTVNG,sMsgError)



        If (not sMsgError.Equals("")) OR lstFondos.Count = 0  then 
           

           If not sMsgError.Equals("") then 
              Dim errorBit = eventoBit.GuardarError ("No se pudieron obtener los fondos")
              errorBit.GuardarDetalle ("Descripción",sMsgError)           
              MessageBox.Show ("No se pudieron obtener los fondos, vuelva a intentarlo o verifique el código:" & errorBit.IdError & "-" & errorBit.IdRegEvento , "Consulta de Saldos",MessageBoxButton.OK,MessageBoxImage.Exclamation)         
          End If



           grdFondoSal.ItemsSource = Nothing 
           grdFondoSal.UpdateLayout()

            txtSaldoDispsal.Text = ""
            txtOrdenPendsal.Text = ""
            txtPendingCashsal.Text = ""
            txtPendindAdjsal.Text = ""
            txtSalDecalogsal.Text = ""    
            txtCanSolSal.Text = ""                    
            txtSaldoActualPS.Text = ""
            
            txtSaldoXSolicitar.Text = ""
            txtCanSolest.Text = ""


            eventoBit.ActualizarFechaFinDelEvento ()
             Mouse.OverrideCursor = Nothing 
            Exit sub
        End If

        



        Try


           
           If not PEJSelActual is Nothing then 
               distribEnTrabajo = lstDistribTotal.Find(Function(x) x.IdPEJ = PEJSelActual.PartidaEJId)
           Else 
               distribEnTrabajo  = Nothing 
           End If
           

           
            If chkComisiones.IsChecked = true then 
               lstSaldosDistrib = negocio.ObtenerSaldosXFondo(lstFondos,SaldoEstimado,distribEnTrabajo, lstComisionFondo)
            else
               lstSaldosDistrib = negocio.ObtenerSaldosXFondo(lstFondos,SaldoEstimado,distribEnTrabajo, Nothing )
            End If
            
           




           grdFondoSal.ItemsSource = lstSaldosDistrib  
           grdFondoSal.UpdateLayout()


          CargarSaldosTotalesTVNG(lstSaldosDistrib, idTVNG, eventoBit)


        Catch ex As Exception

          Dim errorBit = eventoBit.GuardarError ("No se pudieron obtener los Saldos")
          errorBit.GuardarDetalle ("Descripción",ex.Message )           
           MessageBox.Show ("No se pudieron obtener los Saldos, revisar código:" & errorBit.IdError & "-" & errorBit.IdRegEvento, "Consulta de Saldos",MessageBoxButton.OK,MessageBoxImage.Exclamation)
           grdFondoSal.ItemsSource = Nothing 
           grdFondoSal.UpdateLayout()

           txtSaldoDispsal.Text = ""
           txtOrdenPendsal.Text = ""
           txtPendingCashsal.Text = ""
           txtPendindAdjsal.Text = ""
           txtSalDecalogsal.Text = ""
           txtCanSolSal.Text = "" 
           txtSaldoActualPS.Text = ""

           txtSaldoXSolicitar.Text = ""
           txtCanSolest.Text = ""
        End Try
         
        
  End If

  eventoBit.ActualizarFechaFinDelEvento () 
  
  Mouse.OverrideCursor = Nothing 

End Sub

Private Sub btnRefreshSelTVNG_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles btnRefreshSelTVNG.Click

   Dim indexSel As Integer =  cmbTVNGDistrib.SelectedIndex 
   cmbTVNGDistrib.SelectedIndex = -1
   cmbTVNGDistrib.SelectedIndex = indexSel


End Sub

Private Sub CargarSaldosTotalesTVNG(ByRef lstFondosDistribSal As List(Of CTFondosDistribLiq ), ByVal idTVNG As Integer, Optional ByRef eventoBit As CSBitEvento = Nothing)
Dim CantidadActualPS As Decimal = 0 

Dim SaldoTotal    As Decimal = 0
Dim SaldoXDistrib As Decimal = 0 
Dim SaldoXSol     As Decimal = 0

Dim lstBitDetalle = New  List(Of CTBitEventoDet ) 

        Try


            txtSaldoDispsal.Text   = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("SalDisponible"), lstFondosDistribSal).ToString("$ ##,##0.00")
            txtOrdenPendsal.Text   = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("OrdenPend"), lstFondosDistribSal).ToString("$ ##,##0.00")
            txtPendingCashsal.Text = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("PendingCash"), lstFondosDistribSal).ToString("$ ##,##0.00")
            txtPendindAdjsal.Text  = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("PendingCashAjust"), lstFondosDistribSal).ToString("$ ##,##0.00")
            txtSalDecalogsal.Text  = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("SaldoDecalogT"), lstFondosDistribSal).ToString("$ ##,##0.00")

            SaldoTotal             = negocio.ObtenerImporteTotal(CTFondosDistribLiq.ObtenerPosiciones("SaldoDecalogCalculado"), lstFondosDistribSal)
            txtCanSolSal.Text      = SaldoTotal.ToString("$ ##,##0.00")
            txtCanSolest.Text      = SaldoTotal.ToString("$ ##,##0.00")

            'txtSaldoActualPS
            Dim lstPsSal as List(Of CTPartidaSolicitud) =  BSO.LstPS.Findall(Function(x) x.TvngId = idTVNG and (x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.LIBERADA or x.EstatusActualPS = CTPartidaSolicitud.enumEstatusPS.EN_DISTRIBUCION))
            If  lstPsSal is Nothing  then     
                txtSaldoActualPS.Text = 0 
                 SaldoXSol = SaldoTotal - SaldoXDistrib
                 txtSaldoXSolicitar.Text = SaldoXSol.ToString ("$ ##,##0.00")

                         
                  lstBitDetalle.Add(New CTBitEventoDet ("ID TVNG",idTVNG))
                  lstBitDetalle.Add(New CTBitEventoDet ("Saldo Total",txtCanSolest.Text))
                  lstBitDetalle.Add(New CTBitEventoDet ("Saldo PendienteXDistrib",txtSaldoActualPS.Text))
                  lstBitDetalle.Add(New CTBitEventoDet ("Saldo X Solicitar",txtSaldoXSolicitar.Text))
                  eventoBit.GuardarDetalles (lstBitDetalle)

                Exit Sub 
            End If
            
            if lstPsSal.Count = 0 then 
                txtSaldoActualPS.Text = 0 
                SaldoXSol = SaldoTotal - SaldoXDistrib
                txtSaldoXSolicitar.Text = SaldoXSol.ToString ("$ ##,##0.00")


                lstBitDetalle.Add(New CTBitEventoDet ("ID TVNG",idTVNG))
                lstBitDetalle.Add(New CTBitEventoDet ("Saldo Total",txtCanSolest.Text))
                lstBitDetalle.Add(New CTBitEventoDet ("Saldo PendienteXDistrib",txtSaldoActualPS.Text))
                lstBitDetalle.Add(New CTBitEventoDet ("Saldo X Solicitar",txtSaldoXSolicitar.Text))
                eventoBit.GuardarDetalles (lstBitDetalle)

                Exit Sub 
            End If

            For Each ps As CTPartidaSolicitud  In lstPsSal 
                CantidadActualPS += ps.CantidadActualPS 
            Next
            SaldoXDistrib = CantidadActualPS


            txtSaldoActualPS.Text = CantidadActualPS.ToString ("$ ##,##0.00")  

            SaldoXSol = SaldoTotal - SaldoXDistrib
            txtSaldoXSolicitar.Text = SaldoXSol.ToString ("$ ##,##0.00")  


        Catch ex As Exception
            Dim errorBit = eventoBit.GuardarError ("Error en CargarSaldosTotalesTVNG")
            errorBit.GuardarDetalle ("Descripción",ex.Message)
            MessageBox.Show("No se pudo obtener los importes totales. Verificar el código: " & errorBit.IdError & "-" & errorBit.IdRegEvento , "Saldos totales", MessageBoxButton.OK, MessageBoxImage.Exclamation)
             SaldoXSol = SaldoTotal - SaldoXDistrib
             txtSaldoXSolicitar.Text = SaldoXSol.ToString ("$ ##,##0.00")
        End Try


              
        lstBitDetalle.Add(New CTBitEventoDet ("ID TVNG",idTVNG))
        lstBitDetalle.Add(New CTBitEventoDet ("Saldo Total",txtCanSolest.Text))
        lstBitDetalle.Add(New CTBitEventoDet ("Saldo PendienteXDistrib",txtSaldoActualPS.Text))
        lstBitDetalle.Add(New CTBitEventoDet ("Saldo X Solicitar",txtSaldoXSolicitar.Text))
        eventoBit.GuardarDetalles (lstBitDetalle)


    End Sub



Private Sub grdFondoSal_MouseRightButtonUp(ByVal sender As System.Object , ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles grdFondoSal.MouseRightButtonUp


   Dim objDepend As DependencyObject = e.OriginalSource
   Dim celda As DataGridCell = Nothing


        Me.grdFondoSal.ContextMenu = Nothing
        While Not objDepend Is Nothing

            If objDepend.GetType().Name = "DataGridCell" Then
                celda = objDepend

                If celda.IsSelected = False Then
                    Me.grdFondoSal.UnselectAllCells()
                    celda.IsSelected = True
                End If

                celda.Focus()

              
                Me.grdFondoSal.ContextMenu = AgregarMenuContextualSal(ConfigMenuContextual.SOLOCOPIADO)
               
                Exit While
            End If

            objDepend = VisualTreeHelper.GetParent(objDepend)
        End While

End Sub

Private Sub grdFondoSal_PreviewKeyDown(ByVal sender As System.Object , ByVal e As System.Windows.Input.KeyEventArgs) Handles grdFondoSal.PreviewKeyDown

      If e.Key = Key.Apps Then           
         Me.grdFondoInter.ContextMenu = AgregarMenuContextual(ConfigMenuContextual.SOLOCOPIADO)            
     End If


     If Keyboard.Modifiers = ModifierKeys.Control AndAlso e.Key = Key.C Then
           Try
               If copiarCeldas(Me.grdFondoSal, "General.CTFondosDistribLiq") = False Then
                   e.Handled = True 'Se indica que el evento ha sido manejado antes del mensaje, ya que este renderiza la pantalla
                   MessageBox.Show("El rango de celdas seleccionado no es correcto", "Copiar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
               End If

           Catch ex As Exception
               e.Handled = True
               MessageBox.Show("Error TI500. Error al intentar copiar celdas: " & ex.Message, "Copiado", MessageBoxButton.OK, MessageBoxImage.Error)
           End Try

     End If

End Sub


Private Function AgregarMenuContextualSal(ByVal opcion As ConfigMenuContextual) As ContextMenu
      Dim miMenuContextual As New ContextMenu
      Dim mnuCopia As New System.Windows.Controls.MenuItem
      Dim mnuPegar As New System.Windows.Controls.MenuItem



      mnuCopia.Header = "Copiar"
      miMenuContextual.Items.Add(mnuCopia)
      AddHandler mnuCopia.Click, AddressOf mnuCopiarSal_click


      'Este case esta preparado para extender la funcionalidad de las opciones del menú contextual
      Select Case opcion
          Case ConfigMenuContextual.COPIADO_Y_PEGADO
              mnuPegar.Header = "Pegar"
              miMenuContextual.Items.Add(mnuPegar)
              AddHandler mnuPegar.Click, AddressOf mnuPegar_click
      End Select

      Return miMenuContextual

End Function


Private Sub mnuCopiarSal_click(ByVal sender As Object, ByVal e As RoutedEventArgs)

      Try
          If copiarCeldas(Me.grdFondoSal, "General.CTFondosDistribLiq") = False Then
              MessageBox.Show("El rango de celdas seleccionado no es correcto", "Copiar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
          End If
      Catch ex As Exception
          MessageBox.Show("Error TI500. Error al intentar copiar celdas: " & ex.Message, "Copiado", MessageBoxButton.OK, MessageBoxImage.Error)
      End Try

End Sub





#End Region



#Region "COMISIONES"


Private Sub btnCargarComisiones_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles btnCargarComisiones.Click
   Dim aplicacion    As Microsoft.Office.Interop.Excel._Application
   Dim libro         As Microsoft.Office.Interop.Excel.Workbook
   Dim hoja          As Microsoft.Office.Interop.Excel.Worksheet
   Dim rango         As Microsoft.Office.Interop.Excel .Range
   Dim NumReg        As Integer



  Dim resultadoDialog As Boolean
  Dim sRutaArchivo    As String  = ""
  Dim dialog = new Microsoft.Win32.OpenFileDialog()
  


  '1) Seleccionar la ruta del archivo 
  dialog.FileName = ""
  dialog.DefaultExt= "xls"
  dialog.Filter = "Excel documents|*.xls;*.xlsx"
  dialog.Multiselect =False 

  resultadoDialog = dialog.ShowDialog()
  
  If resultadoDialog = True then 
    sRutaArchivo = dialog.FileName
  Else 
     MessageBox.Show("No se pudo obtener la ruta del archivo","Carga de comisiones",MessageBoxButton.OK,MessageBoxImage.Exclamation)
     Exit sub
  End If


  '2) Se crea una instancia de Excel
  Try
      aplicacion = CreateObject("Excel.Application")        
  Catch ex As Exception
     MessageBox.Show("No se pudo leer el archivo: " & ex.Message,"Carga de comisiones",MessageBoxButton.OK,MessageBoxImage.Exclamation)
     Exit Sub 
  End Try
   

  '3) se abre el libro y la hoja
   Try
       libro = Aplicacion.Workbooks.Open(sRutaArchivo)
       hoja = libro.Sheets(1)

   Catch ex As Exception     
       MessageBox.Show("No se pudo leer el archivo: " & ex.Message, "Carga archivo", MessageBoxButton.OK, MessageBoxImage.Error)
       aplicacion.Quit()
       ReleaseObject(aplicacion)
       GC.Collect()
      Exit Sub
   End Try

 


  '4) Se carga la lista de las comisiones

   rango = hoja.UsedRange
   NumReg  = rango.Rows.Count
   

   If NumReg <= 0 then 
      MessageBox.Show("Archivo vacio", "Carga archivo", MessageBoxButton.OK, MessageBoxImage.Error)
      ReleaseObject(hoja)
      libro.Close(False, Type.Missing, Type.Missing)
      ReleaseObject(libro)
      aplicacion.Quit()
      ReleaseObject(aplicacion)
      GC.Collect()
      Exit sub
   End If

   Try

       lstComisionFondo.Clear()

      For i = 2 to NumReg 
         lstComisionFondo.Add(New CTComisionFondo(hoja.Cells(i,1).Value2,hoja.Cells(i,2).Value2,hoja.Cells(i,3).Value2))
      Next
      grdComisionFondo.ItemsSource = lstComisionFondo 
      grdComisionFondo.Items.Refresh()
      grdComisionFondo.UpdateLayout()

   Catch ex As Exception
      MessageBox.Show("Error al cargar la información: " & ex.Message, "Carga archivo", MessageBoxButton.OK, MessageBoxImage.Error)
   Finally
    ReleaseObject(hoja)
    libro.Close(False, Type.Missing, Type.Missing)
    ReleaseObject(libro)
    aplicacion.Quit()
    ReleaseObject(aplicacion)
    GC.Collect()
   End Try
      
End Sub

Private Sub btnLimpiarComisiones_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles btnLimpiarComisiones.Click

   lstComisionFondo.Clear()
   grdComisionFondo.ItemsSource = lstComisionFondo 
   grdComisionFondo.Items.Refresh()
   grdComisionFondo.UpdateLayout()

End Sub


Public Sub ReleaseObject(ByVal o As Object)
      Try
          While(System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
          End While
      Catch
      Finally
          o = Nothing
      End Try
  End Sub


#End Region




    Protected Overrides Sub Finalize()


        MyBase.Finalize()
    End Sub

Private Sub Page_Unloaded(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Unloaded
           DistribucionTotalG = lstDistribTotal
End Sub
End Class



Public Class CCondicionNumNegativoFL
    Implements IValueConverter


    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        If IsNumeric(value) Then
            Dim valor As Double = CType(value, Double)

            If valor < 0 Then
                Return Brushes.Red
            Else
                Return Brushes.Black
            End If
        Else
            Return Brushes.Black
        End If


    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New Exception
    End Function






End Class




Public Class CInhabilitarIntermediario
    Implements IValueConverter

   
 Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
       '******************Solucion por memoria*****************

       Dim Idpej = CType (value,long)

       Dim pej =   BSO.LstPEJ.Find (Function(x) x.PartidaEJId = Idpej) 

       If  pej is Nothing  then 
          Return true
       End If
       
           


       If  pej.EstatusPEJ.CantidadXDistrib  <= 0   then             
             return false
        else
            Return true
        End If 
       
       
       '****************Solucion por DB*******************
       
       ' Dim sMsgError As String = "" 
       ' Dim MontoItem() As Decimal  
       ' Dim negocio = New CSGeneralDistribLiq ()                                      

        'MontoItem =  negocio.ObtenerMontosDeDistribXPEJ(Idpej, sMsgError)
        
        'If Not sMsgError.Equals ("") then 
        '   Return true
        'End If

        'If MontoItem(2)  <= 0   then             
        '     return false
        ' else
        '    Return true
        'End If 

    End Function

 Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New Exception 
    End Function

End Class